WebDavMainPage.ets 150 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275
  1. import { BreadcrumbItem, RemoteDriveGlobalSearchResult, RemoteDriveManager } from '../common/util/RemoteDriveManager';
  2. import { WebDavAccount } from '../viewmodel/WebDavAccount';
  3. import { Song } from '../viewmodel/Song';
  4. import { RemoteDriveManagerStates } from '../common/enums/RemoteDriveManagerStates';
  5. import Logger from '../common/util/Logger';
  6. import { SymbolGlyphModifier, router, curves } from '@kit.ArkUI';
  7. import { CommonConstants } from '../common/constants/CommonConstants';
  8. import { VideoItem } from '../viewmodel/VideoItem';
  9. import { GlobalContext } from '../common/util/GlobalContext';
  10. import { FileInfo } from '../viewmodel/FileInfo';
  11. import { emitter, deviceInfo } from '@kit.BasicServicesKit';
  12. import { hdsEffect } from '@kit.UIDesignKit';
  13. import { EventConstants } from '../common/constants/EventConstants';
  14. import { LazyDataSource } from '../common/util/LazyDataSource';
  15. import { ArrayUtil, FileUtil, MD5, PreferencesUtil, StrUtil, ToastUtil } from '@pura/harmony-utils';
  16. import { MenuModifier } from '../common/util/AttributeModifierUtil';
  17. import { getRemoteDriveAccountLabel, getRemoteDriveDisplayLabel, getRemoteDrivePlaylistPrefix } from '../common/util/RemoteDriveLabel';
  18. import { RemoteDriveType } from '../common/enums/RemoteDriveType';
  19. import { Utility } from '../common/util/Utility';
  20. import { SettingPage } from './SettingPage';
  21. import { getCloudDiskIcon } from '../dialog/RemoteDriveAccountDialog';
  22. import { CreateFolderDialog } from '../dialog/CreateFolderDialog';
  23. import { UploadMusicPage } from './UploadMusicPage';
  24. import { FFmpeg } from '@sj/ffmpeg';
  25. import FileManager from '../common/util/FileManager';
  26. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  27. import { mergeCoverWithPriority, setVideoUrlForSong } from '../common/util/RemotePlayerUtil';
  28. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  29. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  30. import { Playlist } from '../viewmodel/Playlist';
  31. import PlaylistTable from '../common/util/PlaylistTable';
  32. import MediaTable from '../common/util/MediaTable';
  33. import { DownloadCenterManager, DownloadCenterTask } from '../common/util/DownloadCenterManager';
  34. import { TitleBarPointLightButton } from '../view/PointLight/TitleBarPointLightButton';
  35. import { DownloadCenter } from '../view/DownloadCenter';
  36. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  37. import { SearchHistoryUtil } from '../common/util/SearchHistoryUtil';
  38. import { PlayingIndicator } from '../view/PlayingIndicator';
  39. import { buildWebDavVisibleThumbPrefetchWindow, WebDavThumbPrefetchRange } from '../common/util/WebDavThumbPrefetchHelper';
  40. import { buildWebDavSongItemRenderKey } from '../common/util/WebDavListRenderHelper';
  41. import { MusicPlaybackController } from '../controller/MusicPlaybackController';
  42. interface WebDavMetadataUpdatePayload {
  43. filePath: string;
  44. pixelMapPath?: string;
  45. isCustomCover?: number;
  46. md5Str?: string;
  47. name?: string;
  48. artist?: string;
  49. }
  50. interface RemoteThumbSource {
  51. playUrl: string;
  52. headers: Map<string, string>;
  53. }
  54. const TAG = 'heanup WebDavMainPage';
  55. const REMOTE_THUMB_CACHE_DIR: string = 'remote_thumbs';
  56. const REMOTE_THUMB_CAPTURE_SECONDS: string = '1.2';
  57. const WEBDAV_PROGRESSIVE_RELOAD_THRESHOLD: number = 180;
  58. const WEBDAV_PROGRESSIVE_RELOAD_INITIAL_COUNT: number = 20;
  59. const WEBDAV_PROGRESSIVE_RELOAD_BATCH_SIZE: number = 20;
  60. const WEBDAV_PROGRESSIVE_RELOAD_DELAY_MS: number = 32;
  61. const WEBDAV_VISIBLE_THUMB_PREFETCH_DELAY_MS: number = 120;
  62. // WebDAV歌曲数据全局内存存储
  63. let globalWebdavVideoItems: VideoItem[] = [];
  64. let globalWebdavCurrentPlayIndex: number = 0;
  65. let globalRemoteThumbFfmpegQueue: Promise<void> = Promise.resolve();
  66. // 导出函数供LocalMusic访问
  67. export function getWebdavVideoItems(): VideoItem[] {
  68. return globalWebdavVideoItems;
  69. }
  70. export function getWebdavCurrentPlayIndex(): number {
  71. return globalWebdavCurrentPlayIndex;
  72. }
  73. export function setWebdavPlaylist(items: VideoItem[], startIndex: number): void {
  74. globalWebdavVideoItems = items.slice();
  75. globalWebdavCurrentPlayIndex = startIndex;
  76. }
  77. export function clearWebdavVideoItems(): void {
  78. globalWebdavVideoItems = [];
  79. globalWebdavCurrentPlayIndex = 0;
  80. }
  81. // URL解码函数
  82. function decodeUrlEncodedString(encodedStr: string): string {
  83. try {
  84. return decodeURIComponent(encodedStr);
  85. } catch (error) {
  86. // 如果解码失败,返回原始字符串
  87. return encodedStr;
  88. }
  89. }
  90. @Preview
  91. @Entry
  92. @Component
  93. export struct WebDavMainPage {
  94. @State appName: string = ''
  95. @State isShowUploadFile: boolean = false
  96. @State isShowTitleBar: boolean = true //是否显示分类导航条
  97. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  98. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  99. @State isCustomizeBg: boolean = false //自定义背景界面
  100. @State isHomeBgFollowMusicCover: boolean = true //主页背景随当前播放封面
  101. @StorageProp('isLandscape') isLandscape: boolean = false;
  102. @State blurValue: number = 0 //背景模糊
  103. @State bgBrightness: number = 0 //背景亮度
  104. @State customizeBgPath: string | undefined = '';
  105. @StorageProp('customizeMusicBgPath') customizeMusicBgPath: string = '';
  106. private listScroller: ListScroller = new ListScroller()
  107. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  108. searchController: SearchController = new SearchController()
  109. private searchTicket: number = 0;
  110. @StorageProp('animationState') animationState: AnimationStatus= AnimationStatus.Running
  111. @State isSearchMode: boolean = false
  112. @StorageLink('currentSong') @Watch('onHomeBgCurrentSongChange') currentSong: VideoItem | undefined = undefined;
  113. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  114. @State webdavManager: RemoteDriveManager = RemoteDriveManager.getInstance();
  115. @State accounts: WebDavAccount[] = [];
  116. @Prop @Watch('onSwitchAccount') selectedAccount: WebDavAccount;
  117. private songs: VideoItem[] = [];
  118. @State dataSource:LazyDataSource<VideoItem> = new LazyDataSource(this.songs)
  119. @Link mType: number;
  120. @Link offsetX: number;
  121. @Link isShowDrawer: boolean;
  122. @State isLoading: boolean = false;
  123. @State isRefreshingCache: boolean = false;
  124. @State isDirectoryNavigationLoading: boolean = false;
  125. private webDavFiles: FileInfo[] = []; // 原始目录数据保持为普通字段,避免大数组响应式代理卡顿
  126. @StorageProp('themeColor') themeColor: string = CommonConstants.DEFAULT_THEME_COLOR;
  127. @StorageProp('isDarkMode') isDarkMode: boolean = false;
  128. @State currentDirectoryPath: string = '';
  129. @State breadcrumbs:BreadcrumbItem[] = []//面包屑导航
  130. @State private pointLightOptions: hdsEffect.PointLightOptions | undefined = undefined
  131. @State private activePointLightItemKey: string = ''
  132. @State visibleFoldersState: FileInfo[] = []; // 改为普通状态变量
  133. @State isShowFileName: boolean = false//是否显示文件名
  134. @State isLongNameRoLL: boolean = true//长歌名滚动
  135. @State sortType: number = 0 //默认排序方式
  136. @Consume isMultiSelect: boolean
  137. @State selectedSongs: VideoItem[] = []
  138. @State selectedFolders: FileInfo[] = []
  139. @State isAllSelected: boolean = false
  140. @State isDeletingSelection: boolean = false
  141. @State ignoreTapAfterExitMultiSelect: boolean = false
  142. @State isShowSongPropertySheet: boolean = false
  143. @State songForPropertySheet: VideoItem | undefined = undefined
  144. @State rootPath: string = ''
  145. @State isShowDownloadCenter: boolean = false
  146. @State downloadCenterTabIndex: number[] = [0]
  147. @State downloadCenterRefreshVersion: number = 0
  148. @State downloadCenterActiveTasks: DownloadCenterTask[] = []
  149. @State downloadCenterCompletedTasks: DownloadCenterTask[] = []
  150. @State isSearchLoading: boolean = false
  151. private readonly downloadFolderName: string = '下载'
  152. private readonly metadataUpdateEvent: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  153. private thumbnailTaskToken: number = 0;
  154. private thumbnailRunningKeys: Set<string> = new Set<string>();
  155. private visibleListStartIndex: number = -1;
  156. private visibleListEndIndex: number = -1;
  157. private scheduledThumbPrefetchTimer: number = -1;
  158. private lastVisibleThumbStart: number = -1;
  159. private lastVisibleThumbEndExclusive: number = -1;
  160. private readonly downloadCenterManager: DownloadCenterManager = DownloadCenterManager.getInstance();
  161. private readonly downloadCenterListener: () => void = (): void => {
  162. this.scheduleDownloadCenterRefresh();
  163. };
  164. private downloadCenterRefreshTimer: number = -1;
  165. private displayReloadToken: number = 0;
  166. private pendingDirectoryRefreshToken: number = 0;
  167. private playbackController: MusicPlaybackController = MusicPlaybackController.getInstance()
  168. private async runSerializedThumbnailFfmpeg(task: () => Promise<void>): Promise<void> {
  169. const nextTask: Promise<void> = globalRemoteThumbFfmpegQueue.then(async (): Promise<void> => {
  170. await task();
  171. }, async (): Promise<void> => {
  172. await task();
  173. });
  174. globalRemoteThumbFfmpegQueue = nextTask.catch((): void => {});
  175. await nextTask;
  176. }
  177. async onSwitchAccount(){
  178. console.log('heanup 切换账户:', this.selectedAccount.name);
  179. this.cancelPendingDirectoryRefresh();
  180. this.resetRemoteThumbPrefetchState();
  181. this.searchTicket++;
  182. this.searchText = '';
  183. this.filteredList = [];
  184. this.filteredFolderList = [];
  185. this.isSearchMode = false;
  186. this.isSearchLoading = false;
  187. this.songs = [];
  188. this.visibleFoldersState = [];
  189. this.updateListData(this.songs)
  190. this.exitMultiSelect();
  191. // 注意:不再需要清空全局上下文,因为LocalMusic已改用实例变量缓存
  192. // 当新账户加载时,新的认证信息会自动覆盖旧的
  193. Logger.info(TAG, 'heanup 切换账户,准备加载新账户文件');
  194. this.currentDirectoryPath = this.selectedAccount.filepath || '/';
  195. this.scheduleDirectoryRefresh(this.selectedAccount.filepath,
  196. () => this.webdavManager.loadFilesInfoFromAccount(this.selectedAccount), '加载文件失败');
  197. this.breadcrumbs = this.webdavManager.getBreadcrumbs();
  198. }
  199. updateListData(mList:Array<VideoItem>, noSort?: boolean, shouldScrollToTop: boolean = true){
  200. if (!noSort) {
  201. this.sortType = PreferencesUtil.getNumberSync('webDavSortType', 0)
  202. this.doSortType(this.sortType, shouldScrollToTop)
  203. return
  204. }
  205. this.refreshDisplaySongs(mList, shouldScrollToTop)
  206. }
  207. private refreshDisplaySongs(mList: Array<VideoItem>, shouldScrollToTop: boolean = true): void {
  208. const reloadToken: number = ++this.displayReloadToken;
  209. this.invalidateRemoteThumbPrefetchRange()
  210. const displayItems: Array<VideoItem> = mList ? [...mList] : [];
  211. if (displayItems.length <= WEBDAV_PROGRESSIVE_RELOAD_THRESHOLD) {
  212. this.dataSource.pushArrayData(displayItems)
  213. if (shouldScrollToTop && displayItems.length > 0) {
  214. setTimeout(() => {
  215. if (reloadToken !== this.displayReloadToken) {
  216. return
  217. }
  218. this.listScroller.scrollToIndex(0)
  219. }, 120)
  220. }
  221. return
  222. }
  223. const initialItems: Array<VideoItem> = displayItems.slice(0, WEBDAV_PROGRESSIVE_RELOAD_INITIAL_COUNT)
  224. this.dataSource.pushArrayData(initialItems)
  225. if (shouldScrollToTop && initialItems.length > 0) {
  226. setTimeout(() => {
  227. if (reloadToken !== this.displayReloadToken) {
  228. return
  229. }
  230. this.listScroller.scrollToIndex(0)
  231. }, 80)
  232. }
  233. let cursor: number = initialItems.length
  234. const appendNextBatch = (): void => {
  235. if (reloadToken !== this.displayReloadToken) {
  236. return
  237. }
  238. if (cursor >= displayItems.length) {
  239. return
  240. }
  241. const nextBatch: Array<VideoItem> = displayItems.slice(cursor, cursor + WEBDAV_PROGRESSIVE_RELOAD_BATCH_SIZE)
  242. this.dataSource.appendArrayData(nextBatch)
  243. cursor += nextBatch.length
  244. if (cursor < displayItems.length) {
  245. setTimeout(() => {
  246. appendNextBatch()
  247. }, WEBDAV_PROGRESSIVE_RELOAD_DELAY_MS)
  248. }
  249. }
  250. setTimeout(() => {
  251. appendNextBatch()
  252. }, WEBDAV_PROGRESSIVE_RELOAD_DELAY_MS)
  253. }
  254. private cancelPendingDirectoryRefresh(): void {
  255. this.pendingDirectoryRefreshToken += 1
  256. }
  257. private startDirectoryNavigationLoading(): void {
  258. this.isDirectoryNavigationLoading = true
  259. }
  260. private stopDirectoryNavigationLoading(): void {
  261. this.isDirectoryNavigationLoading = false
  262. }
  263. private scheduleDirectoryRefresh(_targetPath: string | undefined, loadAction: () => Promise<void>,
  264. errorPrefix: string): void {
  265. this.cancelPendingDirectoryRefresh()
  266. this.startDirectoryNavigationLoading()
  267. const refreshToken: number = this.pendingDirectoryRefreshToken
  268. this.isLoading = true
  269. this.isRefreshingCache = false
  270. const executeLoad = (): void => {
  271. if (refreshToken !== this.pendingDirectoryRefreshToken) {
  272. return
  273. }
  274. void loadAction().catch((error: Error) => {
  275. if (refreshToken !== this.pendingDirectoryRefreshToken) {
  276. return
  277. }
  278. Logger.error(TAG, `${errorPrefix}: ${error.message}`)
  279. this.isLoading = false
  280. this.isRefreshingCache = false
  281. this.stopDirectoryNavigationLoading()
  282. })
  283. }
  284. executeLoad()
  285. }
  286. private buildThumbnailIdentity(item: VideoItem): string {
  287. const accountId: string = item.webdav_account_id ? item.webdav_account_id : '';
  288. const relPath: string = item.remote_rel_path ? item.remote_rel_path : '';
  289. return `${item.type}:${accountId}:${relPath}:${item.filePath}`;
  290. }
  291. private async ensureThumbnailCacheDir(): Promise<string> {
  292. const context = getContext(this);
  293. const cacheDir: string = `${context.filesDir}/${REMOTE_THUMB_CACHE_DIR}`;
  294. await FileManager.createDir(cacheDir);
  295. return cacheDir;
  296. }
  297. private async resolveRemoteThumbPath(item: VideoItem): Promise<string> {
  298. const cacheDir: string = await this.ensureThumbnailCacheDir();
  299. const identity: string = this.buildThumbnailIdentity(item);
  300. const hashName: string = MD5.digestSync(identity);
  301. return `${cacheDir}/${hashName}.jpg`;
  302. }
  303. private buildFfmpegHeadersArg(headers: Map<string, string>): string {
  304. if (!headers || headers.size <= 0) {
  305. return '';
  306. }
  307. const lines: string[] = [];
  308. headers.forEach((value: string, key: string): void => {
  309. if (StrUtil.isEmpty(key) || StrUtil.isEmpty(value)) {
  310. return;
  311. }
  312. lines.push(`${key}: ${value}`);
  313. });
  314. if (lines.length <= 0) {
  315. return '';
  316. }
  317. return `${lines.join('\r\n')}\r\n`;
  318. }
  319. private buildRemoteThumbFfmpegCmd(playUrl: string, headersArg: string, outputPath: string): string[] {
  320. const commands: string[] = ['ffmpeg', '-y', '-ss', REMOTE_THUMB_CAPTURE_SECONDS];
  321. const networkArgs: string[] = this.buildRemoteFfmpegNetworkArgs(playUrl);
  322. for (let index: number = 0; index < networkArgs.length; index += 1) {
  323. commands.push(networkArgs[index]);
  324. }
  325. if (StrUtil.isNotEmpty(headersArg)) {
  326. commands.push('-headers', headersArg);
  327. }
  328. commands.push(
  329. '-i', playUrl,
  330. '-frames:v', '1',
  331. '-vf', 'scale=320:-2',
  332. '-q:v', '4',
  333. outputPath
  334. );
  335. return commands;
  336. }
  337. private buildRemoteAudioCoverFfmpegCmd(playUrl: string, headersArg: string, outputPath: string): string[] {
  338. const commands: string[] = ['ffmpeg', '-y'];
  339. const networkArgs: string[] = this.buildRemoteFfmpegNetworkArgs(playUrl);
  340. for (let index: number = 0; index < networkArgs.length; index += 1) {
  341. commands.push(networkArgs[index]);
  342. }
  343. if (StrUtil.isNotEmpty(headersArg)) {
  344. commands.push('-headers', headersArg);
  345. }
  346. commands.push(
  347. '-i', playUrl,
  348. '-map', '0:v:0',
  349. '-frames:v', '1',
  350. '-q:v', '4',
  351. outputPath
  352. );
  353. return commands;
  354. }
  355. private buildRemoteFfmpegNetworkArgs(playUrl: string): string[] {
  356. if (StrUtil.isEmpty(playUrl)) {
  357. return [];
  358. }
  359. const lowerPlayUrl: string = playUrl.toLowerCase();
  360. if (!lowerPlayUrl.startsWith('http://') && !lowerPlayUrl.startsWith('https://')) {
  361. return [];
  362. }
  363. return ['-rw_timeout', '15000000', '-probesize', '1048576', '-analyzeduration', '2000000'];
  364. }
  365. private sanitizeFfmpegCommands(commands: string[]): string[] {
  366. const safeCommands: string[] = [];
  367. for (let index: number = 0; index < commands.length; index++) {
  368. const value: string = commands[index];
  369. if (value === undefined || value === null) {
  370. Logger.warn(TAG, `缩略图命令存在空参数 index=${index}`);
  371. continue;
  372. }
  373. const text: string = `${value}`;
  374. if (text.length <= 0) {
  375. Logger.warn(TAG, `缩略图命令存在空字符串参数 index=${index}`);
  376. continue;
  377. }
  378. safeCommands.push(text);
  379. }
  380. return safeCommands;
  381. }
  382. private async executeSafeFfmpeg(commands: string[]): Promise<void> {
  383. // 兼容部分版本 @sj/ffmpeg 对第二个参数空值处理不安全的问题
  384. await FFmpeg.execute(commands, {});
  385. }
  386. private normalizeThumbImageSource(path: string): string {
  387. if (StrUtil.isEmpty(path)) {
  388. return '';
  389. }
  390. if (path.startsWith('http://') || path.startsWith('https://') || path.startsWith('file://')) {
  391. return path;
  392. }
  393. if (path.startsWith('/')) {
  394. return fileUri.getUriFromPath(path);
  395. }
  396. return path;
  397. }
  398. private normalizeThumbLocalPath(path: string): string {
  399. if (StrUtil.isEmpty(path)) {
  400. return '';
  401. }
  402. if (path.startsWith('file://')) {
  403. try {
  404. return new fileUri.FileUri(path).path;
  405. } catch (error) {
  406. const err: Error = error as Error;
  407. Logger.warn(TAG, `缩略图URI转路径失败 uri=${path}, error=${err.message}`);
  408. return '';
  409. }
  410. }
  411. return path;
  412. }
  413. private isThumbCacheValid(localPath: string): boolean {
  414. if (StrUtil.isEmpty(localPath)) {
  415. return false;
  416. }
  417. if (!FileUtil.accessSync(localPath)) {
  418. return false;
  419. }
  420. try {
  421. const stat: fileIo.Stat = fileIo.statSync(localPath);
  422. if (stat.size <= 1024) {
  423. Logger.warn(TAG, `缩略图缓存文件过小,判定无效 path=${localPath}, size=${stat.size}`);
  424. return false;
  425. }
  426. if (this.isImageMagicValid(localPath)) {
  427. return true;
  428. }
  429. Logger.warn(TAG, `缩略图缓存文件头无效,判定无效 path=${localPath}, size=${stat.size}`);
  430. } catch (error) {
  431. const err: Error = error as Error;
  432. Logger.warn(TAG, `缩略图缓存校验失败 path=${localPath}, error=${err.message}`);
  433. }
  434. return false;
  435. }
  436. private isImageMagicValid(localPath: string): boolean {
  437. let file: fileIo.File | undefined = undefined;
  438. try {
  439. file = fileIo.openSync(localPath, fileIo.OpenMode.READ_ONLY);
  440. const headerBuffer: ArrayBuffer = new ArrayBuffer(12);
  441. const readLen: number = fileIo.readSync(file.fd, headerBuffer);
  442. if (readLen < 4) {
  443. return false;
  444. }
  445. const bytes: Uint8Array = new Uint8Array(headerBuffer);
  446. const isJpg: boolean = bytes[0] === 0xFF && bytes[1] === 0xD8 && bytes[2] === 0xFF;
  447. const isPng: boolean = readLen >= 8 &&
  448. bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47 &&
  449. bytes[4] === 0x0D && bytes[5] === 0x0A && bytes[6] === 0x1A && bytes[7] === 0x0A;
  450. const isGif: boolean = readLen >= 4 &&
  451. bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38;
  452. const isBmp: boolean = bytes[0] === 0x42 && bytes[1] === 0x4D;
  453. const isWebp: boolean = readLen >= 12 &&
  454. bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 &&
  455. bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50;
  456. return isJpg || isPng || isGif || isBmp || isWebp;
  457. } catch (error) {
  458. const err: Error = error as Error;
  459. Logger.warn(TAG, `缩略图文件头校验失败 path=${localPath}, error=${err.message}`);
  460. return false;
  461. } finally {
  462. if (file !== undefined) {
  463. try {
  464. fileIo.closeSync(file);
  465. } catch (error) {
  466. const err: Error = error as Error;
  467. Logger.warn(TAG, `关闭缩略图文件失败 path=${localPath}, error=${err.message}`);
  468. }
  469. }
  470. }
  471. }
  472. private removeInvalidThumbCache(localPath: string): void {
  473. if (StrUtil.isEmpty(localPath) || !FileUtil.accessSync(localPath)) {
  474. return;
  475. }
  476. try {
  477. fileIo.unlinkSync(localPath);
  478. Logger.info(TAG, `已删除无效缩略图缓存 path=${localPath}`);
  479. } catch (error) {
  480. const err: Error = error as Error;
  481. Logger.warn(TAG, `删除无效缩略图缓存失败 path=${localPath}, error=${err.message}`);
  482. }
  483. }
  484. private resolveFileNameForTypeCheck(item: VideoItem): string {
  485. const rawName: string = item.fileName ?? item.remote_rel_path ?? item.filePath;
  486. if (StrUtil.isEmpty(rawName)) {
  487. return '';
  488. }
  489. const hashIndex = rawName.indexOf('#');
  490. const queryIndex = rawName.indexOf('?');
  491. let endIndex = rawName.length;
  492. if (queryIndex >= 0) {
  493. endIndex = queryIndex;
  494. }
  495. if (hashIndex >= 0 && hashIndex < endIndex) {
  496. endIndex = hashIndex;
  497. }
  498. return rawName.substring(0, endIndex);
  499. }
  500. private isVideoMediaItem(item: VideoItem): boolean {
  501. if (item.mimeType && item.mimeType.toLowerCase().startsWith('video/')) {
  502. return true;
  503. }
  504. const fileNameForCheck: string = this.resolveFileNameForTypeCheck(item);
  505. return Utility.isVideoByExtension(fileNameForCheck);
  506. }
  507. private refreshThumbItem(item: VideoItem): void {
  508. const dataIndex: number = this.dataSource.dataArray.indexOf(item);
  509. if (dataIndex >= 0) {
  510. this.dataSource.notifyDataChange(dataIndex);
  511. }
  512. }
  513. private getDisplayedFolderCount(): number {
  514. return this.isSearchMode ? this.filteredFolderList.length : this.visibleFoldersState.length
  515. }
  516. private stopScheduledRemoteThumbPrefetch(): void {
  517. if (this.scheduledThumbPrefetchTimer >= 0) {
  518. clearTimeout(this.scheduledThumbPrefetchTimer)
  519. this.scheduledThumbPrefetchTimer = -1
  520. }
  521. }
  522. // 保留当前视口索引,但让新的列表内容可以重新触发同一可见区间的封面补全。
  523. private invalidateRemoteThumbPrefetchRange(): void {
  524. this.stopScheduledRemoteThumbPrefetch()
  525. this.thumbnailTaskToken += 1
  526. this.thumbnailRunningKeys.clear()
  527. this.lastVisibleThumbStart = -1
  528. this.lastVisibleThumbEndExclusive = -1
  529. }
  530. // 列表数据源切换时需要显式取消旧任务,避免后台继续为已经离开的可见区生成封面。
  531. private resetRemoteThumbPrefetchState(): void {
  532. this.invalidateRemoteThumbPrefetchRange()
  533. this.visibleListStartIndex = -1
  534. this.visibleListEndIndex = -1
  535. }
  536. private updateVisibleRemoteThumbRange(start: number, end: number): void {
  537. this.visibleListStartIndex = start
  538. this.visibleListEndIndex = end
  539. this.scheduleRemoteThumbPrefetch()
  540. }
  541. private async prepareRemoteThumbSource(item: VideoItem): Promise<RemoteThumbSource> {
  542. let playUrl: string = item.filePath;
  543. if (StrUtil.isNotEmpty(playUrl)) {
  544. const lowerPath = playUrl.toLowerCase();
  545. const isDirectPath = lowerPath.startsWith('http://') || lowerPath.startsWith('https://') ||
  546. lowerPath.startsWith('/') || lowerPath.startsWith('file://');
  547. if (!isDirectPath) {
  548. try {
  549. playUrl = await setVideoUrlForSong(item, {
  550. extractCover: false,
  551. extractLyric: false,
  552. extractAudioInfo: false
  553. });
  554. } catch (error) {
  555. Logger.warn(TAG, `解析缩略图播放地址失败 name=${item.name}, error=${(error as Error).message}`);
  556. }
  557. }
  558. }
  559. const headers: Map<string, string> = await this.webdavManager.buildHttpHeadersWithAccountId(item, playUrl);
  560. const source: RemoteThumbSource = {
  561. playUrl: playUrl,
  562. headers: headers
  563. };
  564. return source;
  565. }
  566. private async tryResolveRemoteMusicCover(item: VideoItem, token: number): Promise<void> {
  567. if (item.isCustomCover === 1 && StrUtil.isNotEmpty(item.pixelMapPath)) {
  568. this.refreshThumbItem(item);
  569. return;
  570. }
  571. const coverPath: string = await this.resolveRemoteThumbPath(item);
  572. if (this.isThumbCacheValid(coverPath)) {
  573. mergeCoverWithPriority(item, this.normalizeThumbImageSource(coverPath));
  574. this.refreshThumbItem(item);
  575. return;
  576. }
  577. this.removeInvalidThumbCache(coverPath);
  578. const source: RemoteThumbSource = await this.prepareRemoteThumbSource(item);
  579. if (StrUtil.isEmpty(source.playUrl)) {
  580. return;
  581. }
  582. const headersArg: string = this.buildFfmpegHeadersArg(source.headers);
  583. const rawCommands: string[] = this.buildRemoteAudioCoverFfmpegCmd(source.playUrl, headersArg, coverPath);
  584. const commands: string[] = this.sanitizeFfmpegCommands(rawCommands);
  585. if (commands.length < 2) {
  586. return;
  587. }
  588. await this.runSerializedThumbnailFfmpeg(async (): Promise<void> => {
  589. if (token !== this.thumbnailTaskToken) {
  590. return;
  591. }
  592. await this.executeSafeFfmpeg(commands);
  593. });
  594. if (token !== this.thumbnailTaskToken) {
  595. return;
  596. }
  597. if (this.isThumbCacheValid(coverPath)) {
  598. mergeCoverWithPriority(item, this.normalizeThumbImageSource(coverPath));
  599. this.refreshThumbItem(item);
  600. }
  601. }
  602. private async generateRemoteVideoThumb(item: VideoItem, token: number): Promise<void> {
  603. if (token !== this.thumbnailTaskToken) {
  604. return;
  605. }
  606. const identity: string = this.buildThumbnailIdentity(item);
  607. if (this.thumbnailRunningKeys.has(identity)) {
  608. return;
  609. }
  610. this.thumbnailRunningKeys.add(identity);
  611. try {
  612. const isVideoFile: boolean = this.isVideoMediaItem(item);
  613. if (!isVideoFile) {
  614. await this.tryResolveRemoteMusicCover(item, token);
  615. return;
  616. }
  617. const thumbPath: string = await this.resolveRemoteThumbPath(item);
  618. if (this.isThumbCacheValid(thumbPath)) {
  619. mergeCoverWithPriority(item, this.normalizeThumbImageSource(thumbPath));
  620. this.refreshThumbItem(item);
  621. return;
  622. }
  623. this.removeInvalidThumbCache(thumbPath);
  624. const source = await this.prepareRemoteThumbSource(item);
  625. if (StrUtil.isEmpty(source.playUrl)) {
  626. return;
  627. }
  628. const headersArg: string = this.buildFfmpegHeadersArg(source.headers);
  629. const rawCommands: string[] = this.buildRemoteThumbFfmpegCmd(source.playUrl, headersArg, thumbPath);
  630. const commands: string[] = this.sanitizeFfmpegCommands(rawCommands);
  631. if (commands.length < 2) {
  632. return;
  633. }
  634. await this.runSerializedThumbnailFfmpeg(async (): Promise<void> => {
  635. if (token !== this.thumbnailTaskToken) {
  636. return;
  637. }
  638. await this.executeSafeFfmpeg(commands);
  639. });
  640. if (token !== this.thumbnailTaskToken) {
  641. return;
  642. }
  643. if (this.isThumbCacheValid(thumbPath)) {
  644. mergeCoverWithPriority(item, this.normalizeThumbImageSource(thumbPath));
  645. this.refreshThumbItem(item);
  646. }
  647. } catch (error) {
  648. const err: Error = error as Error;
  649. Logger.info(TAG, `远程缩略图/封面生成失败 name=${item.name}, error=${err.message}`);
  650. } finally {
  651. this.thumbnailRunningKeys.delete(identity);
  652. }
  653. }
  654. private scheduleRemoteThumbPrefetch(): void {
  655. if (this.isLoading || this.isRefreshingCache) {
  656. this.stopScheduledRemoteThumbPrefetch()
  657. this.thumbnailTaskToken += 1
  658. this.thumbnailRunningKeys.clear()
  659. return
  660. }
  661. const totalSongs: number = this.dataSource.totalCount()
  662. const visibleWindow = buildWebDavVisibleThumbPrefetchWindow(totalSongs, this.getDisplayedFolderCount(),
  663. this.visibleListStartIndex, this.visibleListEndIndex)
  664. if (!visibleWindow.hasVisibleSongs) {
  665. this.stopScheduledRemoteThumbPrefetch()
  666. this.thumbnailTaskToken += 1
  667. this.thumbnailRunningKeys.clear()
  668. return
  669. }
  670. const range: WebDavThumbPrefetchRange = visibleWindow.range
  671. const isSameVisibleRange: boolean = range.start === this.lastVisibleThumbStart &&
  672. range.endExclusive === this.lastVisibleThumbEndExclusive
  673. if (isSameVisibleRange) {
  674. return
  675. }
  676. this.lastVisibleThumbStart = range.start
  677. this.lastVisibleThumbEndExclusive = range.endExclusive
  678. this.stopScheduledRemoteThumbPrefetch()
  679. const token: number = this.thumbnailTaskToken + 1
  680. this.thumbnailTaskToken = token
  681. this.thumbnailRunningKeys.clear()
  682. this.scheduledThumbPrefetchTimer = setTimeout((): void => {
  683. this.scheduledThumbPrefetchTimer = -1
  684. if (token !== this.thumbnailTaskToken) {
  685. return
  686. }
  687. const mediaItems: VideoItem[] = this.dataSource.dataArray.slice(range.start, range.endExclusive)
  688. if (mediaItems.length <= 0) {
  689. return
  690. }
  691. void this.runRemoteThumbPrefetchQueue(mediaItems, token)
  692. }, WEBDAV_VISIBLE_THUMB_PREFETCH_DELAY_MS)
  693. }
  694. private async runRemoteThumbPrefetchQueue(items: VideoItem[], token: number): Promise<void> {
  695. for (let index: number = 0; index < items.length; index += 1) {
  696. if (token !== this.thumbnailTaskToken) {
  697. return;
  698. }
  699. const item: VideoItem = items[index];
  700. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  701. const currentThumbRef: string = item.pixelMapPath ? item.pixelMapPath : '';
  702. if (currentThumbRef.startsWith('http')) {
  703. continue;
  704. }
  705. const currentThumbPath: string = this.normalizeThumbLocalPath(currentThumbRef);
  706. if (StrUtil.isNotEmpty(currentThumbPath) && this.isThumbCacheValid(currentThumbPath)) {
  707. continue;
  708. }
  709. }
  710. await this.generateRemoteVideoThumb(item, token);
  711. }
  712. }
  713. // 更新可见文件夹列表
  714. private updateVisibleFolders(): void {
  715. try {
  716. // 安全检查webDavFiles
  717. if (!this.webDavFiles || !Array.isArray(this.webDavFiles)) {
  718. this.visibleFoldersState = [];
  719. return;
  720. }
  721. const allFolders = this.webDavFiles.filter(f => f.isDirectory);
  722. const isFlatFolderAccount = this.selectedAccount?.webType === RemoteDriveType.Navidrome
  723. || this.selectedAccount?.webType === RemoteDriveType.Jellyfin
  724. || this.selectedAccount?.webType === RemoteDriveType.Emby;
  725. if (isFlatFolderAccount) {
  726. const sortedNavFolders = allFolders.sort((a, b) => a.fileName.localeCompare(b.fileName));
  727. this.visibleFoldersState = sortedNavFolders;
  728. return;
  729. }
  730. const visible: FileInfo[] = [];
  731. for (let i = 0; i < allFolders.length; i++) {
  732. const folder = allFolders[i];
  733. // 安全检查folder对象
  734. if (!folder || typeof folder.fileName !== 'string') {
  735. continue;
  736. }
  737. let shouldShow = this.isDirectChildOfCurrentPath(folder);
  738. if (shouldShow) {
  739. visible.push(folder);
  740. }
  741. }
  742. console.log('更新文件夹列表:', visible);
  743. this.visibleFoldersState = visible;
  744. } catch (error) {
  745. Logger.error(TAG, '更新文件夹列表失败:', error.toString());
  746. this.visibleFoldersState = [];
  747. }
  748. this.isShowTitleBar = true
  749. }
  750. private isSongSelected(song: VideoItem): boolean {
  751. return this.selectedSongs.some(item => item.filePath === song.filePath);
  752. }
  753. private resolveFolderSelectionKey(folder: FileInfo): string {
  754. return folder.href;
  755. }
  756. private isFolderSelected(folder: FileInfo): boolean {
  757. const key = this.resolveFolderSelectionKey(folder);
  758. return this.selectedFolders.some(item => this.resolveFolderSelectionKey(item) === key);
  759. }
  760. private getSelectableSongs(): VideoItem[] {
  761. return this.isSearchMode ? this.filteredList : this.songs;
  762. }
  763. private getSelectableFolders(): FileInfo[] {
  764. return this.isSearchMode ? this.filteredFolderList : this.visibleFoldersState;
  765. }
  766. private getSelectedEntryCount(): number {
  767. return this.selectedSongs.length + this.selectedFolders.length;
  768. }
  769. private hasSelectedFolders(): boolean {
  770. return this.selectedFolders.length > 0;
  771. }
  772. private canOperateOnSelectedSongs(): boolean {
  773. return this.selectedSongs.length > 0 && !this.hasSelectedFolders() && !this.isDeletingSelection;
  774. }
  775. private updateAllSelectedState(): void {
  776. const totalSelectable = this.getSelectableSongs().length + this.getSelectableFolders().length;
  777. const totalSelected = this.getSelectedEntryCount();
  778. this.isAllSelected = totalSelected > 0 && totalSelected === totalSelectable;
  779. }
  780. private enterMultiSelect(song: VideoItem): void {
  781. if (!this.isMultiSelect) {
  782. this.isMultiSelect = true;
  783. this.selectedSongs = [song];
  784. this.selectedFolders = [];
  785. this.updateAllSelectedState();
  786. return;
  787. }
  788. if (!this.isSongSelected(song)) {
  789. this.toggleSongSelection(song);
  790. }
  791. }
  792. private toggleSongSelection(song: VideoItem): void {
  793. if (!this.isMultiSelect) {
  794. this.isMultiSelect = true;
  795. }
  796. const exists = this.isSongSelected(song);
  797. if (exists) {
  798. const next = this.selectedSongs.filter(item => item.filePath !== song.filePath);
  799. this.selectedSongs = next;
  800. this.updateAllSelectedState();
  801. if (next.length === 0) {
  802. if (this.selectedFolders.length === 0) {
  803. this.exitMultiSelect();
  804. }
  805. }
  806. } else {
  807. const next = [...this.selectedSongs, song];
  808. this.selectedSongs = next;
  809. this.updateAllSelectedState();
  810. }
  811. }
  812. private handleCheckboxSelection(song: VideoItem, checked: boolean): void {
  813. if (this.ignoreTapAfterExitMultiSelect) {
  814. return;
  815. }
  816. if (!this.isMultiSelect) {
  817. this.isMultiSelect = true;
  818. }
  819. const exists = this.isSongSelected(song);
  820. if (checked && !exists) {
  821. this.toggleSongSelection(song);
  822. } else if (!checked && exists) {
  823. this.toggleSongSelection(song);
  824. }
  825. }
  826. private enterFolderMultiSelect(folder: FileInfo): void {
  827. if (!this.isMultiSelect) {
  828. this.isMultiSelect = true;
  829. this.selectedFolders = [folder];
  830. this.selectedSongs = [];
  831. this.updateAllSelectedState();
  832. return;
  833. }
  834. if (!this.isFolderSelected(folder)) {
  835. this.toggleFolderSelection(folder);
  836. }
  837. }
  838. private toggleFolderSelection(folder: FileInfo): void {
  839. if (!this.isMultiSelect) {
  840. this.isMultiSelect = true;
  841. }
  842. const key = this.resolveFolderSelectionKey(folder);
  843. const exists = this.selectedFolders.some(item => this.resolveFolderSelectionKey(item) === key);
  844. if (exists) {
  845. const next = this.selectedFolders.filter(item => this.resolveFolderSelectionKey(item) !== key);
  846. this.selectedFolders = next;
  847. this.updateAllSelectedState();
  848. if (next.length === 0 && this.selectedSongs.length === 0) {
  849. this.exitMultiSelect();
  850. }
  851. } else {
  852. this.selectedFolders = [...this.selectedFolders, folder];
  853. this.updateAllSelectedState();
  854. }
  855. }
  856. private handleFolderCheckboxSelection(folder: FileInfo, checked: boolean): void {
  857. if (this.ignoreTapAfterExitMultiSelect) {
  858. return;
  859. }
  860. if (!this.isMultiSelect) {
  861. this.isMultiSelect = true;
  862. }
  863. const exists = this.isFolderSelected(folder);
  864. if (checked && !exists) {
  865. this.toggleFolderSelection(folder);
  866. } else if (!checked && exists) {
  867. this.toggleFolderSelection(folder);
  868. }
  869. }
  870. private toggleSelectAll(): void {
  871. if (this.isAllSelected) {
  872. this.selectedSongs = [];
  873. this.selectedFolders = [];
  874. this.isAllSelected = false;
  875. return;
  876. }
  877. if (!this.isMultiSelect) {
  878. this.isMultiSelect = true;
  879. }
  880. this.selectedSongs = this.getSelectableSongs().slice();
  881. this.selectedFolders = this.getSelectableFolders().slice();
  882. this.updateAllSelectedState();
  883. }
  884. private exitMultiSelect(): void {
  885. this.ignoreTapAfterExitMultiSelect = true;
  886. this.isMultiSelect = false;
  887. this.selectedSongs = [];
  888. this.selectedFolders = [];
  889. this.isAllSelected = false;
  890. setTimeout(() => {
  891. this.isMultiSelect = false;
  892. this.ignoreTapAfterExitMultiSelect = false;
  893. }, 180);
  894. console.info('onecold this.isMultiSelect ' + this.isMultiSelect)
  895. }
  896. private syncSelectionAfterRefresh(): void {
  897. if (!this.isMultiSelect) {
  898. return;
  899. }
  900. const currentSongKeys: Set<string> = new Set(this.getSelectableSongs().map(item => item.filePath));
  901. const filteredSongs = this.selectedSongs.filter(item => currentSongKeys.has(item.filePath));
  902. if (filteredSongs.length !== this.selectedSongs.length) {
  903. this.selectedSongs = filteredSongs;
  904. }
  905. const currentFolderKeys: Set<string> = new Set(
  906. this.getSelectableFolders().map(item => this.resolveFolderSelectionKey(item))
  907. );
  908. const filteredFolders = this.selectedFolders.filter(item =>
  909. currentFolderKeys.has(this.resolveFolderSelectionKey(item))
  910. );
  911. if (filteredFolders.length !== this.selectedFolders.length) {
  912. this.selectedFolders = filteredFolders;
  913. }
  914. this.updateAllSelectedState();
  915. if (filteredSongs.length === 0 && filteredFolders.length === 0) {
  916. this.exitMultiSelect();
  917. }
  918. }
  919. private confirmDeleteSelected(): void {
  920. if (!this.selectedAccount) {
  921. this.getUIContext().getPromptAction().showToast({ message: `请先选择${getRemoteDriveAccountLabel()}` });
  922. return;
  923. }
  924. const totalSelected = this.getSelectedEntryCount();
  925. if (!this.isMultiSelect || totalSelected === 0) {
  926. this.getUIContext().getPromptAction().showToast({ message: '请先选择要删除的文件或文件夹' });
  927. return;
  928. }
  929. this.getUIContext().showAlertDialog({
  930. title: '删除项目',
  931. message: `确定删除选中的${totalSelected}项吗?`,
  932. primaryButton: {
  933. value: '取消',
  934. action: () => {}
  935. },
  936. secondaryButton: {
  937. value: '删除',
  938. fontColor: Color.Red,
  939. action: () => {
  940. void this.performDeleteSelected();
  941. }
  942. }
  943. });
  944. }
  945. private async performDeleteSelected(): Promise<void> {
  946. if (!this.selectedAccount || this.getSelectedEntryCount() === 0) {
  947. return;
  948. }
  949. this.isDeletingSelection = true;
  950. try {
  951. if (this.selectedSongs.length > 0) {
  952. await this.webdavManager.deleteRemoteSongs(this.selectedAccount, this.selectedSongs.slice());
  953. }
  954. if (this.selectedFolders.length > 0) {
  955. await this.webdavManager.deleteRemoteFolders(this.selectedAccount, this.selectedFolders.slice());
  956. }
  957. this.removeSongsLocally(this.selectedSongs.slice())
  958. this.removeFoldersLocally(this.selectedFolders.slice())
  959. this.exitMultiSelect();
  960. this.getUIContext().getPromptAction().showToast({ message: '删除成功' });
  961. } catch (error) {
  962. const err = error as Error;
  963. this.getUIContext().getPromptAction().showToast({ message: `删除失败: ${err.message}` });
  964. } finally {
  965. this.isDeletingSelection = false;
  966. }
  967. }
  968. private confirmDeleteSingleSong(song: VideoItem): void {
  969. if (!this.selectedAccount) {
  970. this.getUIContext().getPromptAction().showToast({ message: `请先选择${getRemoteDriveAccountLabel()}` });
  971. return;
  972. }
  973. this.getUIContext().showAlertDialog({
  974. title: '删除文件',
  975. message: `确定删除 "${song.name}" 吗?`,
  976. primaryButton: {
  977. value: '取消',
  978. action: () => {}
  979. },
  980. secondaryButton: {
  981. value: '删除',
  982. fontColor: Color.Red,
  983. action: () => {
  984. void this.performDeleteSingleSong(song);
  985. }
  986. }
  987. });
  988. }
  989. private async performDeleteSingleSong(song: VideoItem): Promise<void> {
  990. if (!this.selectedAccount) {
  991. return;
  992. }
  993. this.isDeletingSelection = true;
  994. try {
  995. await this.webdavManager.deleteRemoteSongs(this.selectedAccount, [song]);
  996. this.removeSongsLocally([song])
  997. this.getUIContext().getPromptAction().showToast({ message: '删除成功' });
  998. } catch (error) {
  999. const err = error as Error;
  1000. this.getUIContext().getPromptAction().showToast({ message: `删除失败: ${err.message}` });
  1001. } finally {
  1002. this.isDeletingSelection = false;
  1003. }
  1004. }
  1005. private getRemoteFolderDisplayName(folder: FileInfo): string {
  1006. return decodeUrlEncodedString((folder.fileName ?? folder.name ?? '').replace(/\/+$/, ''));
  1007. }
  1008. private confirmDeleteSingleFolder(folder: FileInfo): void {
  1009. if (!this.selectedAccount) {
  1010. this.getUIContext().getPromptAction().showToast({ message: `请先选择${getRemoteDriveAccountLabel()}` });
  1011. return;
  1012. }
  1013. this.getUIContext().showAlertDialog({
  1014. title: '删除文件夹',
  1015. message: `确定删除 "${this.getRemoteFolderDisplayName(folder)}" 吗?`,
  1016. primaryButton: {
  1017. value: '取消',
  1018. action: () => {}
  1019. },
  1020. secondaryButton: {
  1021. value: '删除',
  1022. fontColor: Color.Red,
  1023. action: () => {
  1024. void this.performDeleteSingleFolder(folder);
  1025. }
  1026. }
  1027. });
  1028. }
  1029. private async performDeleteSingleFolder(folder: FileInfo): Promise<void> {
  1030. if (!this.selectedAccount) {
  1031. return;
  1032. }
  1033. this.isDeletingSelection = true;
  1034. try {
  1035. await this.webdavManager.deleteRemoteFolders(this.selectedAccount, [folder]);
  1036. this.removeFoldersLocally([folder])
  1037. this.getUIContext().getPromptAction().showToast({ message: '删除成功' });
  1038. } catch (error) {
  1039. const err = error as Error;
  1040. this.getUIContext().getPromptAction().showToast({ message: `删除失败: ${err.message}` });
  1041. } finally {
  1042. this.isDeletingSelection = false;
  1043. }
  1044. }
  1045. private removeDisplayedRemoteSongsByKeys(keys: Set<string>): void {
  1046. for (let index = this.dataSource.dataArray.length - 1; index >= 0; index--) {
  1047. const item = this.dataSource.dataArray[index]
  1048. if (item && keys.has(item.filePath)) {
  1049. this.dataSource.deleteData(index)
  1050. }
  1051. }
  1052. }
  1053. private syncGlobalWebdavQueueAfterSongRemoval(keys: Set<string>): void {
  1054. if (keys.size <= 0 || !ArrayUtil.isNotEmpty(globalWebdavVideoItems)) {
  1055. return
  1056. }
  1057. const nextQueue = globalWebdavVideoItems.filter((item: VideoItem) => !keys.has(item.filePath))
  1058. if (nextQueue.length === globalWebdavVideoItems.length) {
  1059. return
  1060. }
  1061. const currentPath = this.currentSong?.filePath ?? '';
  1062. let nextIndex = nextQueue.findIndex((item: VideoItem) => item.filePath === currentPath)
  1063. if (nextIndex < 0) {
  1064. nextIndex = nextQueue.length > 0 ? Math.min(globalWebdavCurrentPlayIndex, nextQueue.length - 1) : 0
  1065. }
  1066. globalWebdavVideoItems = nextQueue
  1067. globalWebdavCurrentPlayIndex = nextIndex
  1068. const eventQueueRefresh: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_QUEUE_REFRESH }
  1069. emitter.emit(eventQueueRefresh, { data: { source: 'webdav-delete' } })
  1070. }
  1071. private removeSongsLocally(songs: VideoItem[]): void {
  1072. if (ArrayUtil.isEmpty(songs)) {
  1073. return
  1074. }
  1075. const keys: Set<string> = new Set<string>(songs.map((item: VideoItem) => item.filePath))
  1076. this.songs = this.songs.filter((item: VideoItem) => !keys.has(item.filePath))
  1077. this.webdavManager.webDavSongs = this.songs.slice()
  1078. this.filteredList = this.filteredList.filter((item: VideoItem) => !keys.has(item.filePath))
  1079. this.removeDisplayedRemoteSongsByKeys(keys)
  1080. this.syncGlobalWebdavQueueAfterSongRemoval(keys)
  1081. if (this.isSearchMode && this.searchText.length > 0) {
  1082. this.syncSelectionAfterRefresh()
  1083. } else {
  1084. this.syncSelectionAfterRefresh()
  1085. }
  1086. this.invalidateRemoteThumbPrefetchRange()
  1087. this.scheduleRemoteThumbPrefetch()
  1088. }
  1089. private removeFoldersLocally(folders: FileInfo[]): void {
  1090. if (ArrayUtil.isEmpty(folders)) {
  1091. return
  1092. }
  1093. const keys: Set<string> = new Set<string>(folders.map((item: FileInfo) => this.resolveFolderSelectionKey(item)))
  1094. this.webDavFiles = this.webDavFiles.filter((item: FileInfo) => !keys.has(this.resolveFolderSelectionKey(item)))
  1095. this.webdavManager.webDavFiles = this.webDavFiles.slice()
  1096. this.visibleFoldersState = this.visibleFoldersState.filter((item: FileInfo) =>
  1097. !keys.has(this.resolveFolderSelectionKey(item)))
  1098. this.filteredFolderList = this.filteredFolderList.filter((item: FileInfo) =>
  1099. !keys.has(this.resolveFolderSelectionKey(item)))
  1100. if (this.isSearchMode && this.searchText.length > 0) {
  1101. this.refreshDisplaySongs(this.filteredList)
  1102. } else {
  1103. this.updateVisibleFolders()
  1104. }
  1105. this.syncSelectionAfterRefresh()
  1106. }
  1107. @Builder
  1108. private buildSwipeDeleteAction(onDelete: () => void) {
  1109. Button() {
  1110. Image($r('app.media.delete2'))
  1111. .fillColor(Color.White)
  1112. .width(20)
  1113. .height(20)
  1114. }
  1115. .width(56)
  1116. .height(56)
  1117. .type(ButtonType.Circle)
  1118. .backgroundColor('#E53935')
  1119. .margin(8)
  1120. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.86 })
  1121. .onClick(() => {
  1122. onDelete()
  1123. })
  1124. }
  1125. private canRenameRemoteSong(song: VideoItem): boolean {
  1126. return song.type === CommonConstants.TYPE_WEBDAV ||
  1127. song.type === CommonConstants.TYPE_SMB ||
  1128. song.type === CommonConstants.TYPE_FTP ||
  1129. song.type === CommonConstants.TYPE_BAIDU;
  1130. }
  1131. private canRenameRemoteFolder(): boolean {
  1132. return !!this.selectedAccount &&
  1133. (this.selectedAccount.webType === RemoteDriveType.WebDav ||
  1134. this.selectedAccount.webType === RemoteDriveType.Smb ||
  1135. this.selectedAccount.webType === RemoteDriveType.Ftp ||
  1136. this.selectedAccount.webType === RemoteDriveType.Baidu);
  1137. }
  1138. private getRemoteSongRenameFileName(song: VideoItem): string {
  1139. const rawName = StrUtil.isNotEmpty(song.fileName) ? song.fileName as string : song.name;
  1140. return decodeUrlEncodedString(rawName ?? '');
  1141. }
  1142. private getRemoteSongRenameExtension(song: VideoItem): string {
  1143. const fileName = this.getRemoteSongRenameFileName(song);
  1144. const lastDotIndex = fileName.lastIndexOf('.');
  1145. if (lastDotIndex <= 0) {
  1146. return '';
  1147. }
  1148. return fileName.substring(lastDotIndex);
  1149. }
  1150. private async resolveSongAccountForAction(song: VideoItem): Promise<WebDavAccount | null> {
  1151. if (song.webdav_account_id) {
  1152. const account = await this.webdavManager.getWebDavAccountById(song.webdav_account_id);
  1153. if (account) {
  1154. return account;
  1155. }
  1156. }
  1157. return this.selectedAccount ?? null;
  1158. }
  1159. private showRenameSongDialog(song: VideoItem): void {
  1160. if (!this.canRenameRemoteSong(song)) {
  1161. this.getUIContext().getPromptAction().showToast({ message: '当前文件暂不支持重命名' });
  1162. return;
  1163. }
  1164. const extension = this.getRemoteSongRenameExtension(song);
  1165. const currentThemeColor = this.themeColor;
  1166. this.renameSongDialogController = new CustomDialogController({
  1167. builder: CreateFolderDialog({
  1168. onConfirm: (fileName: string) => {
  1169. if (fileName.trim().length > 0) {
  1170. void this.performRenameRemoteSong(song, fileName.trim());
  1171. } else {
  1172. this.getUIContext().getPromptAction().showToast({ message: '文件名称不能为空' });
  1173. }
  1174. },
  1175. onCancel: () => {
  1176. },
  1177. initialName: this.getRemoteSongRenameFileName(song),
  1178. title: '重命名',
  1179. placeholder: extension.length > 0 ? `请输入文件名称,保留 ${extension} 格式` : '请输入文件名称',
  1180. confirmText: '确定',
  1181. cancelText: '取消',
  1182. themeColor: currentThemeColor
  1183. }),
  1184. autoCancel: true,
  1185. alignment: DialogAlignment.Center,
  1186. customStyle: false
  1187. });
  1188. this.renameSongDialogController.open();
  1189. }
  1190. private showRenameFolderDialog(folder: FileInfo): void {
  1191. if (!this.canRenameRemoteFolder()) {
  1192. this.getUIContext().getPromptAction().showToast({ message: '当前文件夹暂不支持重命名' });
  1193. return;
  1194. }
  1195. const currentThemeColor = this.themeColor;
  1196. this.renameSongDialogController = new CustomDialogController({
  1197. builder: CreateFolderDialog({
  1198. onConfirm: (folderName: string) => {
  1199. if (folderName.trim().length > 0) {
  1200. void this.performRenameRemoteFolder(folder, folderName.trim());
  1201. } else {
  1202. this.getUIContext().getPromptAction().showToast({ message: '文件夹名称不能为空' });
  1203. }
  1204. },
  1205. onCancel: () => {
  1206. },
  1207. initialName: this.getRemoteFolderDisplayName(folder),
  1208. title: '重命名',
  1209. placeholder: '请输入文件夹名称',
  1210. confirmText: '确定',
  1211. cancelText: '取消',
  1212. themeColor: currentThemeColor
  1213. }),
  1214. autoCancel: true,
  1215. alignment: DialogAlignment.Center,
  1216. customStyle: false
  1217. });
  1218. this.renameSongDialogController.open();
  1219. }
  1220. private async performRenameRemoteSong(song: VideoItem, content: string): Promise<void> {
  1221. const nextName = content ? content.trim() : '';
  1222. if (!nextName) {
  1223. this.getUIContext().getPromptAction().showToast({ message: '文件名称不能为空' });
  1224. return;
  1225. }
  1226. const currentFileName = this.getRemoteSongRenameFileName(song);
  1227. if (nextName === currentFileName) {
  1228. return;
  1229. }
  1230. const account = await this.resolveSongAccountForAction(song);
  1231. if (!account) {
  1232. this.getUIContext().getPromptAction().showToast({ message: `请先选择${getRemoteDriveAccountLabel()}` });
  1233. return;
  1234. }
  1235. this.isLoading = true;
  1236. try {
  1237. await this.webdavManager.renameRemoteSong(account, song, nextName);
  1238. await this.webdavManager.loadFilesInfoFromAccount(account, this.currentDirectoryPath || account.filepath || '/');
  1239. this.getUIContext().getPromptAction().showToast({ message: '重命名成功' });
  1240. } catch (error) {
  1241. const err = error as Error;
  1242. this.getUIContext().getPromptAction().showToast({ message: `重命名失败: ${err.message}` });
  1243. } finally {
  1244. this.isLoading = false;
  1245. }
  1246. }
  1247. private async performRenameRemoteFolder(folder: FileInfo, content: string): Promise<void> {
  1248. const nextName = content ? content.trim().replace(/\/+$/, '') : '';
  1249. if (!nextName) {
  1250. this.getUIContext().getPromptAction().showToast({ message: '文件夹名称不能为空' });
  1251. return;
  1252. }
  1253. const currentFolderName = this.getRemoteFolderDisplayName(folder);
  1254. if (nextName === currentFolderName) {
  1255. return;
  1256. }
  1257. if (!this.selectedAccount) {
  1258. this.getUIContext().getPromptAction().showToast({ message: `请先选择${getRemoteDriveAccountLabel()}` });
  1259. return;
  1260. }
  1261. this.isLoading = true;
  1262. try {
  1263. await this.webdavManager.renameRemoteFolder(this.selectedAccount, folder, nextName);
  1264. await this.webdavManager.loadFilesInfoFromAccount(this.selectedAccount,
  1265. this.currentDirectoryPath || this.selectedAccount.filepath || '/');
  1266. this.getUIContext().getPromptAction().showToast({ message: '重命名成功' });
  1267. } catch (error) {
  1268. const err = error as Error;
  1269. this.getUIContext().getPromptAction().showToast({ message: `重命名失败: ${err.message}` });
  1270. } finally {
  1271. this.isLoading = false;
  1272. }
  1273. }
  1274. private addSongToNextPlay(song: VideoItem): void {
  1275. if (!song) {
  1276. return;
  1277. }
  1278. const displayQueue: VideoItem[] = this.getCurrentPlaybackQueue();
  1279. const queue: VideoItem[] = globalWebdavVideoItems && globalWebdavVideoItems.length > 0 ?
  1280. globalWebdavVideoItems : displayQueue;
  1281. if (!queue || queue.length === 0) {
  1282. this.getUIContext().getPromptAction().showToast({ message: '当前列表为空' });
  1283. return;
  1284. }
  1285. const currentPath = this.currentSong?.filePath;
  1286. if (StrUtil.isEmpty(currentPath)) {
  1287. const targetIndex = displayQueue.findIndex((item: VideoItem) => item.filePath === song.filePath);
  1288. if (targetIndex >= 0) {
  1289. this.playSong(song, targetIndex, false);
  1290. this.getUIContext().getPromptAction().showToast({ message: '已开始播放' });
  1291. }
  1292. return;
  1293. }
  1294. if (currentPath === song.filePath) {
  1295. this.getUIContext().getPromptAction().showToast({ message: '当前正在播放这首歌' });
  1296. return;
  1297. }
  1298. let currentIndex = queue.findIndex((item: VideoItem) => item.filePath === currentPath);
  1299. if (currentIndex < 0 && globalWebdavCurrentPlayIndex >= 0 && globalWebdavCurrentPlayIndex < queue.length) {
  1300. currentIndex = globalWebdavCurrentPlayIndex;
  1301. }
  1302. if (currentIndex < 0) {
  1303. currentIndex = 0;
  1304. }
  1305. const existIndex = queue.findIndex((item: VideoItem) => item.filePath === song.filePath);
  1306. if (existIndex >= 0) {
  1307. const movedSong = queue.splice(existIndex, 1)[0];
  1308. if (existIndex < currentIndex) {
  1309. currentIndex -= 1;
  1310. }
  1311. queue.splice(currentIndex + 1, 0, movedSong);
  1312. } else {
  1313. queue.splice(currentIndex + 1, 0, song);
  1314. }
  1315. globalWebdavCurrentPlayIndex = currentIndex;
  1316. globalWebdavVideoItems = queue;
  1317. this.songs = [...queue];
  1318. this.dataSource.pushArrayData(this.songs);
  1319. const eventQueueRefresh: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_QUEUE_REFRESH };
  1320. emitter.emit(eventQueueRefresh, { data: { source: 'webdav' } });
  1321. this.getUIContext().getPromptAction().showToast({ message: '已添加到下一首播放' });
  1322. }
  1323. private cloneSongForDb(song: VideoItem): VideoItem {
  1324. const dbSong = new VideoItem(
  1325. song.name || '',
  1326. song.id || song.filePath,
  1327. song.filePath,
  1328. song.type,
  1329. song.videoSize || 0,
  1330. song.cTime || Utility.getFormatDateStr(new Date(), 'yyyy-MM-dd HH:mm')
  1331. );
  1332. dbSong.parentPath = song.parentPath;
  1333. dbSong.isFav = song.isFav;
  1334. dbSong.size = song.size;
  1335. dbSong.pixelMapPath = song.pixelMapPath;
  1336. dbSong.isCustomCover = song.isCustomCover;
  1337. dbSong.artist = song.artist;
  1338. dbSong.album = song.album;
  1339. dbSong.fileName = song.fileName;
  1340. dbSong.duration = song.duration;
  1341. dbSong.mimeType = song.mimeType;
  1342. dbSong.sampleRate = song.sampleRate;
  1343. dbSong.trackCount = song.trackCount;
  1344. dbSong.lastPlayedStr = song.lastPlayedStr;
  1345. dbSong.playCount = song.playCount;
  1346. dbSong.lyricContent = song.lyricContent;
  1347. dbSong.md5Str = song.md5Str;
  1348. dbSong.extra_json = song.extra_json;
  1349. dbSong.pyStr = song.pyStr;
  1350. dbSong.bit_rate = song.bit_rate;
  1351. dbSong.probe_score = song.probe_score;
  1352. dbSong.year = song.year;
  1353. dbSong.nb_streams = song.nb_streams;
  1354. dbSong.nb_programs = song.nb_programs;
  1355. dbSong.genre = song.genre;
  1356. dbSong.track = song.track;
  1357. dbSong.bits_per_raw_sample = song.bits_per_raw_sample;
  1358. dbSong.channels = song.channels;
  1359. dbSong.channel_layout = song.channel_layout;
  1360. dbSong.start_time = song.start_time;
  1361. dbSong.ALBUMARTIST = song.ALBUMARTIST;
  1362. dbSong.COMPOSER = song.COMPOSER;
  1363. dbSong.LYRICIST = song.LYRICIST;
  1364. dbSong.COMMENT = song.COMMENT;
  1365. dbSong.disc = song.disc;
  1366. dbSong.webdav_account_id = song.webdav_account_id;
  1367. dbSong.remote_rel_path = song.remote_rel_path;
  1368. dbSong.navArtistId = song.navArtistId;
  1369. dbSong.navAlbumId = song.navAlbumId;
  1370. dbSong.baiduFsId = song.baiduFsId;
  1371. dbSong.webdav_id = song.webdav_id;
  1372. dbSong.lyricIndex = song.lyricIndex;
  1373. return dbSong;
  1374. }
  1375. private emitPlaylistRefresh(): void {
  1376. emitter.emit({ eventId: EventConstants.EVENT_PLAYLIST_REFRESH }, {});
  1377. }
  1378. private buildPlaylistSongCandidates(songs: VideoItem[]): VideoItem[] {
  1379. if (!songs || songs.length <= 0) {
  1380. return [];
  1381. }
  1382. const result: VideoItem[] = [];
  1383. const existedPaths: Set<string> = new Set<string>();
  1384. for (let index: number = 0; index < songs.length; index += 1) {
  1385. const song = songs[index];
  1386. if (!song || StrUtil.isEmpty(song.filePath)) {
  1387. continue;
  1388. }
  1389. if (existedPaths.has(song.filePath)) {
  1390. continue;
  1391. }
  1392. existedPaths.add(song.filePath);
  1393. result.push(song);
  1394. }
  1395. return result;
  1396. }
  1397. private async resolvePlaylistSongPaths(mediaTable: MediaTable, songs: VideoItem[]): Promise<string[]> {
  1398. const paths: string[] = [];
  1399. for (let index: number = 0; index < songs.length; index += 1) {
  1400. const song: VideoItem = songs[index];
  1401. const songForDb: VideoItem = this.cloneSongForDb(song);
  1402. if (!songForDb.webdav_account_id && this.selectedAccount?.id) {
  1403. songForDb.webdav_account_id = this.selectedAccount.id.toString();
  1404. }
  1405. if (StrUtil.isEmpty(songForDb.id)) {
  1406. songForDb.id = songForDb.remote_rel_path || songForDb.filePath;
  1407. }
  1408. if (StrUtil.isEmpty(songForDb.remote_rel_path)) {
  1409. songForDb.remote_rel_path = songForDb.id || songForDb.filePath;
  1410. }
  1411. if (StrUtil.isEmpty(songForDb.parentPath) && songForDb.filePath.includes('/')) {
  1412. const pathIndex = songForDb.filePath.lastIndexOf('/');
  1413. if (pathIndex > 0) {
  1414. songForDb.parentPath = songForDb.filePath.substring(0, pathIndex);
  1415. }
  1416. }
  1417. const saved: boolean = await mediaTable.saveOrUpdateWebDavItem(songForDb);
  1418. if (!saved) {
  1419. Logger.warn(TAG, `歌曲入库失败,跳过加入歌单: ${songForDb.filePath}`);
  1420. continue;
  1421. }
  1422. const storedSong: VideoItem | null = await mediaTable.queryVideoByFilePath(songForDb.filePath);
  1423. if (storedSong && StrUtil.isNotEmpty(storedSong.filePath)) {
  1424. paths.push(storedSong.filePath);
  1425. }
  1426. }
  1427. const uniquePaths: string[] = [];
  1428. const pathSet: Set<string> = new Set<string>();
  1429. for (let index: number = 0; index < paths.length; index += 1) {
  1430. const path = paths[index];
  1431. if (StrUtil.isEmpty(path) || pathSet.has(path)) {
  1432. continue;
  1433. }
  1434. pathSet.add(path);
  1435. uniquePaths.push(path);
  1436. }
  1437. return uniquePaths;
  1438. }
  1439. private async openSongsAddToPlaylistDialog(songs: VideoItem[]): Promise<void> {
  1440. const candidateSongs: VideoItem[] = this.buildPlaylistSongCandidates(songs);
  1441. if (candidateSongs.length <= 0) {
  1442. this.getUIContext().getPromptAction().showToast({ message: '请选择要加入歌单的歌曲' });
  1443. return;
  1444. }
  1445. try {
  1446. const uiContext = this.getUIContext();
  1447. const hostCtx = uiContext ? uiContext.getHostContext() : undefined;
  1448. if (!hostCtx) {
  1449. this.getUIContext().getPromptAction().showToast({ message: '无法获取上下文' });
  1450. return;
  1451. }
  1452. const playlistTable: PlaylistTable = new PlaylistTable(hostCtx);
  1453. const mediaTable: MediaTable = new MediaTable(hostCtx);
  1454. await new Promise<void>((resolve) => {
  1455. mediaTable.getRdbStore(hostCtx, () => resolve());
  1456. });
  1457. const playlistSongPaths: string[] = await this.resolvePlaylistSongPaths(mediaTable, candidateSongs);
  1458. if (playlistSongPaths.length <= 0) {
  1459. this.getUIContext().getPromptAction().showToast({ message: '歌曲入库失败,无法添加到歌单' });
  1460. return;
  1461. }
  1462. const resolveSuccessToast = (): string => {
  1463. if (playlistSongPaths.length > 1) {
  1464. return `已添加${playlistSongPaths.length}首到歌单`;
  1465. }
  1466. return '已添加到歌单';
  1467. };
  1468. const openDialog = async (): Promise<void> => {
  1469. const playlists: Playlist[] = await playlistTable.queryAllPlaylists();
  1470. showAddToPlaylistDialog(
  1471. candidateSongs,
  1472. playlists,
  1473. async (playlistId: string) => {
  1474. const success = await playlistTable.addSongsToPlaylist(playlistId, playlistSongPaths);
  1475. if (success) {
  1476. this.emitPlaylistRefresh();
  1477. }
  1478. this.getUIContext().getPromptAction().showToast({ message: success ? resolveSuccessToast() : '歌曲已在该歌单中' });
  1479. },
  1480. () => {},
  1481. () => {
  1482. showCreatePlaylistDialog(
  1483. async (name: string, description: string, coverPath?: string) => {
  1484. const created = await playlistTable.createPlaylist(name, description, coverPath);
  1485. if (!created) {
  1486. this.getUIContext().getPromptAction().showToast({ message: '歌单创建失败' });
  1487. return;
  1488. }
  1489. const target = await playlistTable.queryPlaylistByName(name);
  1490. if (!target) {
  1491. this.getUIContext().getPromptAction().showToast({ message: '未找到新建歌单' });
  1492. return;
  1493. }
  1494. const addSuccess = await playlistTable.addSongsToPlaylist(target.id, playlistSongPaths);
  1495. if (addSuccess) {
  1496. this.emitPlaylistRefresh();
  1497. }
  1498. this.getUIContext().getPromptAction().showToast({ message: addSuccess ? resolveSuccessToast() : '歌曲已在该歌单中' });
  1499. },
  1500. () => {}
  1501. );
  1502. }
  1503. );
  1504. };
  1505. await openDialog();
  1506. } catch (error) {
  1507. const err = error as Error;
  1508. Logger.error(TAG, `打开添加到歌单失败: ${err.message}`);
  1509. this.getUIContext().getPromptAction().showToast({ message: '添加到歌单失败' });
  1510. }
  1511. }
  1512. private async openSelectedSongsAddToPlaylistDialog(): Promise<void> {
  1513. if (!this.isMultiSelect || this.selectedSongs.length <= 0) {
  1514. this.getUIContext().getPromptAction().showToast({ message: '请先选择歌曲' });
  1515. return;
  1516. }
  1517. await this.openSongsAddToPlaylistDialog(this.selectedSongs.slice());
  1518. }
  1519. private async openSongAddToPlaylistDialog(song: VideoItem): Promise<void> {
  1520. if (!song) {
  1521. return;
  1522. }
  1523. await this.openSongsAddToPlaylistDialog([song]);
  1524. }
  1525. private sanitizeDownloadFileName(fileName: string): string {
  1526. const trimmed = (fileName || '').trim();
  1527. const sanitized = trimmed.replace(/[\\/:*?"<>|]/g, '_');
  1528. return sanitized.length > 0 ? sanitized : '未知歌曲.mp3';
  1529. }
  1530. private resolveDownloadFileName(song: VideoItem, sourceUrlOrPath: string): string {
  1531. if (StrUtil.isNotEmpty(song.fileName)) {
  1532. return this.sanitizeDownloadFileName(song.fileName as string);
  1533. }
  1534. if (StrUtil.isNotEmpty(song.name) && (song.name as string).includes('.')) {
  1535. return this.sanitizeDownloadFileName(song.name as string);
  1536. }
  1537. if (StrUtil.isNotEmpty(sourceUrlOrPath)) {
  1538. const purePath = sourceUrlOrPath.split('?')[0];
  1539. const lastSlash = purePath.lastIndexOf('/');
  1540. if (lastSlash >= 0 && lastSlash < purePath.length - 1) {
  1541. const urlName = purePath.substring(lastSlash + 1);
  1542. if (StrUtil.isNotEmpty(urlName)) {
  1543. return this.sanitizeDownloadFileName(urlName);
  1544. }
  1545. }
  1546. }
  1547. const baseName = StrUtil.isNotEmpty(song.name) ? song.name as string : '未知歌曲';
  1548. return this.sanitizeDownloadFileName(`${baseName}.mp3`);
  1549. }
  1550. private buildUniqueDownloadPath(downloadDir: string, fileName: string): string {
  1551. const safeName = this.sanitizeDownloadFileName(fileName);
  1552. const dotIndex = safeName.lastIndexOf('.');
  1553. const hasExt = dotIndex > 0;
  1554. const namePart = hasExt ? safeName.substring(0, dotIndex) : safeName;
  1555. const extPart = hasExt ? safeName.substring(dotIndex) : '';
  1556. let targetPath = `${downloadDir}/${safeName}`;
  1557. let suffix = 1;
  1558. while (FileUtil.accessSync(targetPath)) {
  1559. targetPath = `${downloadDir}/${namePart}(${suffix})${extPart}`;
  1560. suffix += 1;
  1561. }
  1562. return targetPath;
  1563. }
  1564. private async pickDownloadRootPath(): Promise<string> {
  1565. try {
  1566. const documentViewPicker = new picker.DocumentViewPicker();
  1567. const documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD });
  1568. if (!documentSaveResult || documentSaveResult.length === 0) {
  1569. return '';
  1570. }
  1571. const resolvedPath = new fileUri.FileUri(documentSaveResult[0]).path;
  1572. this.rootPath = resolvedPath;
  1573. return resolvedPath;
  1574. } catch (error) {
  1575. const err = error as Error;
  1576. Logger.error(TAG, `选择下载目录失败: ${err.message}`);
  1577. return '';
  1578. }
  1579. }
  1580. private async ensureDownloadDirectory(): Promise<string> {
  1581. let basePath = this.rootPath;
  1582. if (StrUtil.isEmpty(basePath) || !FileUtil.accessSync(basePath)) {
  1583. basePath = await this.pickDownloadRootPath();
  1584. }
  1585. if (StrUtil.isEmpty(basePath)) {
  1586. return '';
  1587. }
  1588. const downloadDir = `${basePath}/${this.downloadFolderName}`;
  1589. if (!FileUtil.accessSync(downloadDir)) {
  1590. await fileIo.mkdir(downloadDir);
  1591. }
  1592. return downloadDir;
  1593. }
  1594. private async upsertDownloadedSongToLibrary(targetPath: string, sourceSong: VideoItem): Promise<void> {
  1595. if (StrUtil.isEmpty(targetPath) || !FileUtil.accessSync(targetPath)) {
  1596. return;
  1597. }
  1598. try {
  1599. const pageContext = getContext(this);
  1600. const mediaModule = await import('../common/util/MediaTable');
  1601. const mediaTable = new mediaModule.default(pageContext);
  1602. await new Promise<void>((resolve) => {
  1603. mediaTable.getRdbStore(pageContext, () => resolve());
  1604. });
  1605. const exists = await mediaTable.isRecordExists(targetPath);
  1606. if (exists) {
  1607. return;
  1608. }
  1609. let mediaItem: VideoItem;
  1610. try {
  1611. mediaItem = await Utility.readMetaInfoFFmpeg(pageContext, targetPath, CommonConstants.TYPE_LOCAL, false);
  1612. } catch (error) {
  1613. Logger.warn(TAG, `下载歌曲读取元数据失败,使用兜底入库: ${(error as Error).message}`);
  1614. mediaItem = new VideoItem(
  1615. sourceSong.name || FileUtil.getFileName(targetPath),
  1616. targetPath,
  1617. targetPath,
  1618. CommonConstants.TYPE_LOCAL,
  1619. 0,
  1620. Utility.getFormatDateStr(new Date(), 'yyyy-MM-dd HH:mm')
  1621. );
  1622. mediaItem.fileName = FileUtil.getFileName(targetPath);
  1623. mediaItem.artist = sourceSong.artist;
  1624. mediaItem.album = sourceSong.album;
  1625. }
  1626. mediaItem.id = targetPath;
  1627. mediaItem.filePath = targetPath;
  1628. mediaItem.type = CommonConstants.TYPE_LOCAL;
  1629. if (StrUtil.isEmpty(mediaItem.fileName)) {
  1630. mediaItem.fileName = FileUtil.getFileName(targetPath);
  1631. }
  1632. if (StrUtil.isEmpty(mediaItem.name)) {
  1633. mediaItem.name = mediaItem.fileName as string;
  1634. }
  1635. if (StrUtil.isEmpty(mediaItem.parentPath)) {
  1636. mediaItem.parentPath = FileUtil.getParentPath(targetPath);
  1637. }
  1638. await new Promise<void>((resolve) => {
  1639. mediaTable.insert(mediaItem, () => resolve());
  1640. });
  1641. emitter.emit({ eventId: EventConstants.EVENT_SCAN_UPDATE }, {});
  1642. } catch (error) {
  1643. Logger.error(TAG, `下载歌曲入库失败: ${(error as Error).message}`);
  1644. }
  1645. }
  1646. private openDownloadCenter(): void {
  1647. this.syncDownloadCenterTasks();
  1648. this.isShowDownloadCenter = true;
  1649. }
  1650. private syncDownloadCenterTasks(): void {
  1651. this.downloadCenterActiveTasks = this.downloadCenterManager.getActiveTasks();
  1652. this.downloadCenterCompletedTasks = this.downloadCenterManager.getCompletedTasks();
  1653. }
  1654. private scheduleDownloadCenterRefresh(): void {
  1655. if (this.downloadCenterRefreshTimer >= 0) {
  1656. return;
  1657. }
  1658. this.downloadCenterRefreshTimer = setTimeout((): void => {
  1659. this.downloadCenterRefreshTimer = -1;
  1660. this.syncDownloadCenterTasks();
  1661. this.downloadCenterRefreshVersion += 1;
  1662. }, 0);
  1663. }
  1664. private stopDownloadCenterRefresh(): void {
  1665. if (this.downloadCenterRefreshTimer >= 0) {
  1666. clearTimeout(this.downloadCenterRefreshTimer);
  1667. this.downloadCenterRefreshTimer = -1;
  1668. }
  1669. }
  1670. private resolveSongDownloadSizeText(song: VideoItem): string {
  1671. if (StrUtil.isNotEmpty(song.size)) {
  1672. return decodeUrlEncodedString(song.size as string);
  1673. }
  1674. if (song.videoSize > 0) {
  1675. return this.formatDownloadBytes(song.videoSize);
  1676. }
  1677. return '';
  1678. }
  1679. private parseSizeTextToBytes(sizeText: string): number {
  1680. if (StrUtil.isEmpty(sizeText)) {
  1681. return 0;
  1682. }
  1683. const normalized = sizeText.trim();
  1684. const match = normalized.match(/([0-9]+(?:\.[0-9]+)?)\s*(B|KB|MB|GB|TB)/i);
  1685. if (!match) {
  1686. return 0;
  1687. }
  1688. const value = parseFloat(match[1]);
  1689. if (!Number.isFinite(value) || value <= 0) {
  1690. return 0;
  1691. }
  1692. const unit = match[2].toUpperCase();
  1693. const factor = this.resolveUnitFactor(unit);
  1694. return Math.floor(value * factor);
  1695. }
  1696. private resolveUnitFactor(unit: string): number {
  1697. switch (unit) {
  1698. case 'KB':
  1699. return 1024;
  1700. case 'MB':
  1701. return 1024 * 1024;
  1702. case 'GB':
  1703. return 1024 * 1024 * 1024;
  1704. case 'TB':
  1705. return 1024 * 1024 * 1024 * 1024;
  1706. case 'B':
  1707. default:
  1708. return 1;
  1709. }
  1710. }
  1711. private formatDownloadBytes(bytes: number): string {
  1712. if (!Number.isFinite(bytes) || bytes <= 0) {
  1713. return '';
  1714. }
  1715. const units: string[] = ['B', 'KB', 'MB', 'GB', 'TB'];
  1716. let size: number = bytes;
  1717. let index: number = 0;
  1718. while (size >= 1024 && index < units.length - 1) {
  1719. size /= 1024;
  1720. index += 1;
  1721. }
  1722. const precision: number = index === 0 ? 0 : 2;
  1723. return `${size.toFixed(precision)} ${units[index]}`;
  1724. }
  1725. private pauseDownloadTask(taskId: string): void {
  1726. if (StrUtil.isEmpty(taskId)) {
  1727. return;
  1728. }
  1729. this.downloadCenterManager.pauseTask(taskId);
  1730. }
  1731. private resumeDownloadTask(taskId: string): void {
  1732. if (StrUtil.isEmpty(taskId)) {
  1733. return;
  1734. }
  1735. this.downloadCenterManager.resumeTask(taskId);
  1736. }
  1737. private deleteDownloadTask(taskId: string): void {
  1738. if (StrUtil.isEmpty(taskId)) {
  1739. return;
  1740. }
  1741. this.downloadCenterManager.deleteTask(taskId);
  1742. this.syncDownloadCenterTasks();
  1743. this.downloadCenterRefreshVersion += 1;
  1744. }
  1745. private buildDownloadedVideoItem(task: DownloadCenterTask): VideoItem {
  1746. const fileName = StrUtil.isNotEmpty(task.fileName) ? task.fileName : FileUtil.getFileName(task.targetPath);
  1747. const title = StrUtil.isNotEmpty(task.title) ? task.title : fileName;
  1748. const item = new VideoItem(
  1749. title,
  1750. task.targetPath,
  1751. task.targetPath,
  1752. CommonConstants.TYPE_LOCAL,
  1753. task.totalBytes,
  1754. '',
  1755. task.sizeText,
  1756. task.coverPath,
  1757. undefined,
  1758. undefined,
  1759. fileName
  1760. );
  1761. item.parentPath = StrUtil.isNotEmpty(task.downloadDir) ? task.downloadDir : FileUtil.getParentPath(task.targetPath);
  1762. item.pixelMapPath = task.coverPath;
  1763. item.size = task.sizeText;
  1764. item.videoSize = task.totalBytes;
  1765. item.type = CommonConstants.TYPE_LOCAL;
  1766. return item;
  1767. }
  1768. private playCompletedDownloadTask(taskId: string): void {
  1769. if (StrUtil.isEmpty(taskId)) {
  1770. return;
  1771. }
  1772. const playableTasks = this.downloadCenterCompletedTasks.filter((task: DownloadCenterTask): boolean => {
  1773. return StrUtil.isNotEmpty(task.targetPath)
  1774. });
  1775. const playlist: VideoItem[] = playableTasks.map((task: DownloadCenterTask): VideoItem => {
  1776. return this.buildDownloadedVideoItem(task)
  1777. });
  1778. if (playlist.length <= 0) {
  1779. this.getUIContext().getPromptAction().showToast({ message: '没有可播放的下载文件' });
  1780. return;
  1781. }
  1782. const startIndex = playableTasks.findIndex((task: DownloadCenterTask): boolean => {
  1783. return task.taskId === taskId;
  1784. });
  1785. if (startIndex < 0 || startIndex >= playlist.length) {
  1786. this.getUIContext().getPromptAction().showToast({ message: '未找到对应下载任务' });
  1787. return;
  1788. }
  1789. setWebdavPlaylist(playlist, startIndex);
  1790. void this.playbackController.playQueue(playlist.slice(), startIndex, 'controller-open').catch((error: Error) => {
  1791. Logger.error(TAG, `下载中心播放失败: ${error.message}`);
  1792. this.getUIContext().getPromptAction().showToast({ message: '播放失败' });
  1793. });
  1794. }
  1795. private async resolveSongDownloadSourceUrl(song: VideoItem): Promise<string> {
  1796. if (song.type === CommonConstants.TYPE_BAIDU && song.webdav_account_id) {
  1797. try {
  1798. const account = await this.webdavManager.getWebDavAccountById(song.webdav_account_id);
  1799. if (account) {
  1800. const dlink = await this.webdavManager.getBaiduDownloadUrl(account, song);
  1801. if (StrUtil.isNotEmpty(dlink)) {
  1802. Logger.info(TAG, `下载中心使用百度直链下载: ${song.name}`);
  1803. return dlink;
  1804. }
  1805. }
  1806. } catch (error) {
  1807. Logger.warn(TAG, `百度下载直链获取失败,回退播放地址: ${(error as Error).message}`);
  1808. }
  1809. }
  1810. if (song.type === CommonConstants.TYPE_WEBDAV) {
  1811. try {
  1812. let account: WebDavAccount | null = null;
  1813. if (song.webdav_account_id) {
  1814. account = await this.webdavManager.getWebDavAccountById(song.webdav_account_id);
  1815. }
  1816. if (!account && this.selectedAccount?.webType === RemoteDriveType.WebDav) {
  1817. account = this.selectedAccount;
  1818. }
  1819. if (account) {
  1820. const relativePath = song.remote_rel_path || song.filePath;
  1821. const fullUrl = WebDavUrlUtil.buildFullUrl(account, relativePath);
  1822. if (StrUtil.isNotEmpty(fullUrl)) {
  1823. Logger.info(TAG, `下载中心使用WebDAV直链下载: ${song.name}, url=${fullUrl}`);
  1824. return fullUrl;
  1825. }
  1826. }
  1827. } catch (error) {
  1828. Logger.warn(TAG, `WebDAV下载直链构建失败,回退播放地址: ${(error as Error).message}`);
  1829. }
  1830. }
  1831. return setVideoUrlForSong(song, {
  1832. context: getContext(this),
  1833. autoParseMusicName: false,
  1834. extractCover: false,
  1835. extractLyric: false,
  1836. extractAudioInfo: false
  1837. });
  1838. }
  1839. private async buildDownloadRequestHeaders(song: VideoItem, sourceUrl: string): Promise<Map<string, string>> {
  1840. if (song.type === CommonConstants.TYPE_BAIDU) {
  1841. const headers = new Map<string, string>();
  1842. // 参考 BaiduFileCache 下载链路,避免复用播放头导致 Range 行为异常
  1843. headers.set('User-Agent', 'pan.baidu.com');
  1844. headers.set('Accept', '*/*');
  1845. headers.set('Connection', 'Keep-Alive');
  1846. return headers;
  1847. }
  1848. return this.webdavManager.buildHttpHeadersWithAccountId(song, sourceUrl);
  1849. }
  1850. private async enqueueSongDownloadWithDirectory(song: VideoItem, downloadDir: string): Promise<string> {
  1851. if (!song) {
  1852. throw new Error('歌曲不存在');
  1853. }
  1854. if (StrUtil.isEmpty(downloadDir)) {
  1855. throw new Error('未选择下载目录');
  1856. }
  1857. const sourceUrl = await this.resolveSongDownloadSourceUrl(song);
  1858. const normalizedSource = sourceUrl.startsWith('file://') ? new fileUri.FileUri(sourceUrl).path : sourceUrl;
  1859. const fileName = this.resolveDownloadFileName(song, normalizedSource);
  1860. const targetPath = this.buildUniqueDownloadPath(downloadDir, fileName);
  1861. const sizeText = this.resolveSongDownloadSizeText(song);
  1862. const expectedBytes = this.parseSizeTextToBytes(sizeText);
  1863. const requestHeaders = await this.buildDownloadRequestHeaders(song, sourceUrl);
  1864. const coverPath = song.pixelMapPath ?? '';
  1865. this.downloadCenterManager.enqueueDownload({
  1866. title: song.name || fileName,
  1867. fileName: fileName,
  1868. coverPath: coverPath,
  1869. sizeText: sizeText,
  1870. expectedBytes: expectedBytes,
  1871. sourceUrl: sourceUrl,
  1872. targetPath: targetPath,
  1873. downloadDir: downloadDir,
  1874. headers: requestHeaders,
  1875. onCompleted: async () => {
  1876. await this.upsertDownloadedSongToLibrary(targetPath, song);
  1877. }
  1878. });
  1879. return fileName;
  1880. }
  1881. private async enqueueSongDownload(song: VideoItem): Promise<void> {
  1882. if (!song) {
  1883. return;
  1884. }
  1885. try {
  1886. const downloadDir = await this.ensureDownloadDirectory();
  1887. if (StrUtil.isEmpty(downloadDir)) {
  1888. this.getUIContext().getPromptAction().showToast({ message: '未选择下载目录' });
  1889. return;
  1890. }
  1891. const fileName: string = await this.enqueueSongDownloadWithDirectory(song, downloadDir);
  1892. this.openDownloadCenter();
  1893. this.getUIContext().getPromptAction().showToast({ message: `已加入下载队列: ${fileName}` });
  1894. } catch (error) {
  1895. const err = error as Error;
  1896. Logger.error(TAG, `加入下载队列失败: ${err.message}`);
  1897. this.getUIContext().getPromptAction().showToast({ message: `下载任务创建失败: ${err.message}` });
  1898. }
  1899. }
  1900. private async enqueueSelectedSongsDownload(): Promise<void> {
  1901. if (!this.isMultiSelect || this.selectedSongs.length <= 0) {
  1902. this.getUIContext().getPromptAction().showToast({ message: '请先选择要下载的歌曲' });
  1903. return;
  1904. }
  1905. const candidates: VideoItem[] = this.buildPlaylistSongCandidates(this.selectedSongs.slice());
  1906. if (candidates.length <= 0) {
  1907. this.getUIContext().getPromptAction().showToast({ message: '没有可下载的歌曲' });
  1908. return;
  1909. }
  1910. try {
  1911. const downloadDir = await this.ensureDownloadDirectory();
  1912. if (StrUtil.isEmpty(downloadDir)) {
  1913. this.getUIContext().getPromptAction().showToast({ message: '未选择下载目录' });
  1914. return;
  1915. }
  1916. let successCount: number = 0;
  1917. let failedCount: number = 0;
  1918. for (let index: number = 0; index < candidates.length; index += 1) {
  1919. const song: VideoItem = candidates[index];
  1920. try {
  1921. await this.enqueueSongDownloadWithDirectory(song, downloadDir);
  1922. successCount += 1;
  1923. } catch (error) {
  1924. failedCount += 1;
  1925. const err = error as Error;
  1926. Logger.error(TAG, `批量下载入队失败: ${(song.name || song.fileName || song.filePath)}, ${err.message}`);
  1927. }
  1928. }
  1929. if (successCount > 0) {
  1930. this.openDownloadCenter();
  1931. this.exitMultiSelect();
  1932. }
  1933. if (successCount > 0 && failedCount <= 0) {
  1934. this.getUIContext().getPromptAction().showToast({ message: `已加入下载队列: ${successCount}首` });
  1935. return;
  1936. }
  1937. if (successCount > 0) {
  1938. this.getUIContext().getPromptAction().showToast({ message: `已加入下载队列${successCount}首,失败${failedCount}首` });
  1939. return;
  1940. }
  1941. this.getUIContext().getPromptAction().showToast({ message: '下载任务创建失败' });
  1942. } catch (error) {
  1943. const err = error as Error;
  1944. Logger.error(TAG, `批量下载失败: ${err.message}`);
  1945. this.getUIContext().getPromptAction().showToast({ message: `批量下载失败: ${err.message}` });
  1946. }
  1947. }
  1948. private buildSongMetaLine(song: VideoItem): string {
  1949. const parts: string[] = [];
  1950. if (StrUtil.isNotEmpty(song.duration)) {
  1951. parts.push(song.duration as string);
  1952. } else if (StrUtil.isNotEmpty(song.size)) {
  1953. parts.push(decodeUrlEncodedString(song.size as string));
  1954. }
  1955. if (parts.length === 0 && StrUtil.isNotEmpty(song.cTime)) {
  1956. parts.push(song.cTime as string);
  1957. }
  1958. return parts.join(' · ');
  1959. }
  1960. private buildSongQualityLabel(song: VideoItem): string {
  1961. if (!song || StrUtil.isEmpty(song.md5Str)) {
  1962. return '';
  1963. }
  1964. const quality = song.md5Str as string;
  1965. return quality.includes('Lossless') ? '无损' : quality;
  1966. }
  1967. // 对话框控制器
  1968. private accountDialogController: CustomDialogController | null = null;
  1969. // 保存事件处理器引用,用于取消订阅
  1970. private eventHandler: (event: string) => void = (event: string) => {
  1971. this.handleWebdavEvent(event);
  1972. };
  1973. initSetting(){
  1974. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  1975. this.isHomeBgFollowMusicCover = PreferencesUtil.getBooleanSync(SettingPage.IS_HOME_BG_FOLLOW_MUSIC_COVER, true)
  1976. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  1977. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  1978. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  1979. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  1980. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  1981. this.sortType = PreferencesUtil.getNumberSync('webDavSortType', 0)
  1982. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  1983. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  1984. this.syncCustomizeMusicBgPath()
  1985. }
  1986. private onHomeBgCurrentSongChange(): void {
  1987. this.syncCustomizeMusicBgPath()
  1988. }
  1989. private syncCustomizeMusicBgPath(): void {
  1990. if (!this.isHomeBgFollowMusicCover) {
  1991. return
  1992. }
  1993. const coverPath: string = this.currentSong?.pixelMapPath ?? ''
  1994. AppStorage.setOrCreate('customizeMusicBgPath', coverPath)
  1995. }
  1996. private isMusicCoverHomeBackgroundActive(): boolean {
  1997. return this.isHomeBgFollowMusicCover && this.customizeMusicBgPath.length > 0
  1998. }
  1999. aboutToAppear(): void {
  2000. Utility.getAppName(getContext(this)).then((appName: string) => {
  2001. this.appName = appName
  2002. })
  2003. this.initSetting()
  2004. let eventSetting: emitter.InnerEvent = { eventId: 333 }
  2005. // 监听广播事件(通用设置配置更新)
  2006. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  2007. this.initSetting()
  2008. });
  2009. // 加载账户列表
  2010. this.loadAccounts();
  2011. this.loadFiles()
  2012. this.breadcrumbs = this.webdavManager.getBreadcrumbs();
  2013. // 订阅WebDAV状态变化
  2014. this.webdavManager.subscribe(this.eventHandler);
  2015. this.downloadCenterManager.subscribe(this.downloadCenterListener);
  2016. this.subscribeWebDavMetadataUpdates();
  2017. // 监听手势返回事件
  2018. let eventBackSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_DISK }
  2019. emitter.on(eventBackSwipeBack, (eventData: emitter.EventData) => {
  2020. console.info('onecold', ' 收到 EVENT_SWIPE_BACK_DISK 事件');
  2021. // 如果在详情视图模式,退出详情视图
  2022. this.goBack()
  2023. });
  2024. }
  2025. aboutToDisappear(): void {
  2026. // 取消订阅
  2027. this.cancelPendingDirectoryRefresh();
  2028. this.resetRemoteThumbPrefetchState();
  2029. this.stopDirectoryNavigationLoading();
  2030. this.webdavManager.unsubscribe(this.eventHandler);
  2031. this.downloadCenterManager.unsubscribe(this.downloadCenterListener);
  2032. this.stopDownloadCenterRefresh();
  2033. emitter.off(EventConstants.EVENT_WEBDAV_METADATA_UPDATED);
  2034. }
  2035. // 处理WebDAV事件
  2036. private handleWebdavEvent(event: string): void {
  2037. switch (event) {
  2038. case RemoteDriveManagerStates.LoadFilesInfoStart:
  2039. this.resetRemoteThumbPrefetchState();
  2040. this.startDirectoryNavigationLoading();
  2041. if (this.dataSource.totalCount() > 0 || this.visibleFoldersState.length > 0) {
  2042. this.isLoading = false;
  2043. this.isRefreshingCache = true;
  2044. } else {
  2045. this.isLoading = true;
  2046. this.isRefreshingCache = false;
  2047. }
  2048. break;
  2049. case RemoteDriveManagerStates.LoadFilesInfoSucceed:
  2050. const shouldScrollToTop: boolean = !this.isRefreshingCache;
  2051. this.resetRemoteThumbPrefetchState();
  2052. this.songs = this.webdavManager.webDavSongs;
  2053. // 直接引用webdavManager的数组,避免@Observed序列化问题
  2054. this.webDavFiles = this.webdavManager.webDavFiles;
  2055. this.currentDirectoryPath = this.webdavManager.currentPath || '/';
  2056. this.isLoading = false;
  2057. this.isRefreshingCache = false;
  2058. this.stopDirectoryNavigationLoading();
  2059. // 更新可见文件夹列表
  2060. this.updateVisibleFolders();
  2061. this.breadcrumbs = this.webdavManager.getBreadcrumbs();
  2062. this.syncSelectionAfterRefresh();
  2063. if (this.isSearchMode && this.searchText.length > 0) {
  2064. void this.applyGlobalSearch(this.searchText, ++this.searchTicket);
  2065. } else {
  2066. this.restoreCurrentDirectorySearchView(shouldScrollToTop);
  2067. }
  2068. // promptAction.showToast({
  2069. // message: '加载成功: ' + this.webDavFiles.filter(f => f.isDirectory).length + '个文件夹, ' + this.songs.length + '首歌曲'
  2070. // });
  2071. break;
  2072. case RemoteDriveManagerStates.LoadFilesInfoFailed:
  2073. this.isLoading = false;
  2074. this.isRefreshingCache = false;
  2075. this.stopDirectoryNavigationLoading();
  2076. // this.getUIContext().getPromptAction().showToast({ message: '加载失败' });
  2077. break;
  2078. case RemoteDriveManagerStates.InsertAccountSucceed:
  2079. case RemoteDriveManagerStates.EditAccountSucceed:
  2080. case RemoteDriveManagerStates.RemoveAccountSucceed:
  2081. this.loadAccounts();
  2082. break;
  2083. case RemoteDriveManagerStates.GlobalSearchIndexBuildStart:
  2084. case RemoteDriveManagerStates.GlobalSearchIndexUpdated:
  2085. case RemoteDriveManagerStates.GlobalSearchIndexReady:
  2086. if (this.isSearchMode && this.searchText.length > 0) {
  2087. void this.applyGlobalSearch(this.searchText, ++this.searchTicket);
  2088. }
  2089. break;
  2090. case RemoteDriveManagerStates.GlobalSearchIndexFailed:
  2091. this.isSearchLoading = false;
  2092. break;
  2093. }
  2094. }
  2095. private subscribeWebDavMetadataUpdates(): void {
  2096. emitter.on(this.metadataUpdateEvent, (eventData: emitter.EventData) => {
  2097. const payloads = eventData?.data as WebDavMetadataUpdatePayload[] | undefined;
  2098. if (!payloads || payloads.length === 0) {
  2099. Logger.info(TAG, 'WebDav metadata event received but payload empty');
  2100. return;
  2101. }
  2102. Logger.info(TAG, `WebDav metadata event payload count: ${payloads.length}`);
  2103. this.handleWebDavMetadataUpdates(payloads);
  2104. });
  2105. }
  2106. private handleWebDavMetadataUpdates(payloads: WebDavMetadataUpdatePayload[]): void {
  2107. if (!payloads || payloads.length === 0) {
  2108. return;
  2109. }
  2110. Logger.info(TAG, 'handleWebDavMetadataUpdates start');
  2111. const changedIndices: number[] = [];
  2112. for (let i = 0; i < payloads.length; i++) {
  2113. const payload = payloads[i];
  2114. if (!payload || !payload.filePath) {
  2115. continue;
  2116. }
  2117. Logger.info(TAG, `WebDav metadata detail path=${payload.pixelMapPath ?? 'null'}`);
  2118. const changedIndex = this.updateSongMetadata(payload);
  2119. if (changedIndex >= 0) {
  2120. if (changedIndices.indexOf(changedIndex) < 0) {
  2121. changedIndices.push(changedIndex);
  2122. }
  2123. Logger.info(TAG, `metadata updated for ${payload.filePath}`);
  2124. }
  2125. }
  2126. if (changedIndices.length === 0) {
  2127. Logger.info(TAG, 'handleWebDavMetadataUpdates no changes detected');
  2128. return;
  2129. }
  2130. // 元数据回填只刷新变更行,避免后台补封面时整列表反复重建导致卡顿。
  2131. for (let index = 0; index < changedIndices.length; index += 1) {
  2132. const changedIndex = changedIndices[index];
  2133. if (changedIndex >= 0 && changedIndex < this.dataSource.totalCount()) {
  2134. this.dataSource.notifyDataChange(changedIndex);
  2135. }
  2136. }
  2137. Logger.info(TAG, 'handleWebDavMetadataUpdates trigger refresh');
  2138. }
  2139. private updateSongMetadata(payload: WebDavMetadataUpdatePayload): number {
  2140. if (!payload.filePath) {
  2141. return -1;
  2142. }
  2143. const targetIndex = this.findSongIndex(payload.filePath);
  2144. if (targetIndex < 0) {
  2145. return -1;
  2146. }
  2147. const targetSong = this.songs[targetIndex];
  2148. let mutated = false;
  2149. if (mergeCoverWithPriority(targetSong, payload.pixelMapPath, payload.isCustomCover ?? 0)) {
  2150. mutated = true;
  2151. }
  2152. if (payload.md5Str && payload.md5Str.length > 0 && targetSong.md5Str !== payload.md5Str) {
  2153. targetSong.md5Str = payload.md5Str;
  2154. mutated = true;
  2155. }
  2156. if (payload.name && payload.name.length > 0) {
  2157. targetSong.name = payload.name;
  2158. mutated = true;
  2159. }
  2160. if (payload.artist && payload.artist.length > 0) {
  2161. targetSong.artist = payload.artist;
  2162. mutated = true;
  2163. }
  2164. return mutated ? targetIndex : -1;
  2165. }
  2166. private findSongIndex(filePath: string): number {
  2167. for (let i = 0; i < this.songs.length; i++) {
  2168. if (this.songs[i].filePath === filePath) {
  2169. return i;
  2170. }
  2171. }
  2172. return -1;
  2173. }
  2174. // 加载账户列表
  2175. private loadAccounts(): void {
  2176. this.accounts = this.webdavManager.getAllWebDavAccounts();
  2177. }
  2178. // 加载文件列表
  2179. private loadFiles(): void {
  2180. if (!this.selectedAccount) {
  2181. this.getUIContext().getPromptAction().showToast({ message: '请先选择账户' });
  2182. return;
  2183. }
  2184. console.info('heanup '+this.selectedAccount.name+'type '+this.selectedAccount.webType)
  2185. this.scheduleDirectoryRefresh(this.selectedAccount.filepath,
  2186. () => this.webdavManager.loadFilesInfoFromAccount(this.selectedAccount), '加载文件失败')
  2187. }
  2188. // 进入文件夹
  2189. private enterFolder(folder: FileInfo): void {
  2190. const targetPath = this.webdavManager.prepareEnterFolder(folder)
  2191. if (!targetPath || !this.selectedAccount) {
  2192. return
  2193. }
  2194. Logger.info(TAG, `进入文件夹: current=${this.currentDirectoryPath}, target=${targetPath}`)
  2195. this.scheduleDirectoryRefresh(targetPath,
  2196. () => this.webdavManager.loadFilesInfoFromAccount(this.selectedAccount, targetPath), '进入文件夹失败')
  2197. }
  2198. // 检查是否为当前目录的直接子项
  2199. private isDirectChildOfCurrentPath(folder: FileInfo): boolean {
  2200. const currentPath = this.currentDirectoryPath || '';
  2201. // 如果在根目录(currentPath为空或'/'),显示所有第一级文件夹
  2202. if (currentPath === '' || currentPath === '/') {
  2203. const folderPath = folder.href.replace(/\/$/, ''); // 去掉尾部斜杠
  2204. return folder.href.startsWith('/') &&
  2205. folder.href !== '/' &&
  2206. !folderPath.substring(1).includes('/');
  2207. }
  2208. // 非根目录情况,计算相对路径
  2209. let relativePath = folder.href;
  2210. if (currentPath !== '/') {
  2211. relativePath = folder.href.replace(currentPath, '');
  2212. }
  2213. relativePath = relativePath.replace(/^\//, '').replace(/\/$/, '');
  2214. // 只有相对路径不为空且不包含/时才认为是直接子项
  2215. return relativePath !== '' && !relativePath.includes('/');
  2216. }
  2217. // 返回上级目录
  2218. private goBack(): void {
  2219. if(this.webdavManager.canGoBack()){
  2220. const previousPath = this.webdavManager.prepareGoBack()
  2221. if (!previousPath || !this.selectedAccount) {
  2222. return
  2223. }
  2224. Logger.info(TAG, `返回上级目录: current=${this.currentDirectoryPath}, previous=${previousPath}`)
  2225. this.scheduleDirectoryRefresh(previousPath,
  2226. () => this.webdavManager.loadFilesInfoFromAccount(this.selectedAccount, previousPath), '返回失败')
  2227. }else{
  2228. this.getUIContext().animateTo({ duration: 555 }, () => {
  2229. // 动画闭包内控制Image组件的出现和消失
  2230. this.isShowDrawer = !this.isShowDrawer
  2231. this.offsetX = 0
  2232. })
  2233. }
  2234. }
  2235. // 切换账户
  2236. private switchAccount(account: WebDavAccount): void {
  2237. this.selectedAccount = account;
  2238. this.songs = [];
  2239. this.updateListData(this.songs)
  2240. }
  2241. private getCurrentPlaybackQueue(): VideoItem[] {
  2242. if (this.isSearchMode && this.searchText.length > 0 && this.filteredList.length > 0) {
  2243. return this.filteredList;
  2244. }
  2245. return this.songs;
  2246. }
  2247. private resolveSongPlayIndex(song: VideoItem, fallbackIndex: number, queue: VideoItem[]): number {
  2248. if (queue.length <= 0) {
  2249. return -1;
  2250. }
  2251. if (song && StrUtil.isNotEmpty(song.filePath)) {
  2252. for (let i = 0; i < queue.length; i++) {
  2253. if (queue[i].filePath === song.filePath) {
  2254. return i;
  2255. }
  2256. }
  2257. }
  2258. if (fallbackIndex >= 0 && fallbackIndex < queue.length) {
  2259. return fallbackIndex;
  2260. }
  2261. return 0;
  2262. }
  2263. // 播放WebDAV歌曲
  2264. private playSong(song: VideoItem, index: number,isJump:boolean=false): void {
  2265. try {
  2266. const queue: VideoItem[] = this.getCurrentPlaybackQueue();
  2267. Logger.info(TAG, `heanup === WebDAV playSong 方法被调用 ===`);
  2268. Logger.info(TAG, 'heanup 播放指定歌曲: ' + song.name + ', 索引: ' + index);
  2269. Logger.info(TAG, 'heanup 播放队列长度: ' + queue.length);
  2270. const playIndex = this.resolveSongPlayIndex(song, index, queue);
  2271. if (playIndex < 0 || playIndex >= queue.length) {
  2272. this.getUIContext().getPromptAction().showToast({ message: '播放失败,未找到歌曲' });
  2273. Logger.warn(TAG, `heanup 无法定位播放索引: fallback=${index}, songPath=${song.filePath}`);
  2274. return;
  2275. }
  2276. if (playIndex !== index) {
  2277. Logger.info(TAG, `heanup 修正播放索引: fallback=${index}, real=${playIndex}, song=${song.name}`);
  2278. }
  2279. // 检查歌曲是否有webdav_account_id
  2280. Logger.info(TAG, `heanup 播放歌曲的webdav_account_id: ${song.webdav_account_id || '未设置'}`);
  2281. // 确保所有歌曲都设置了正确的webdav_account_id
  2282. if (this.selectedAccount && this.selectedAccount.id) {
  2283. const accountIds = queue.map(s => s.webdav_account_id).filter(id => id);
  2284. Logger.info(TAG, `heanup 当前歌曲列表中有 ${accountIds.length}/${queue.length} 首歌曲设置了webdav_account_id`);
  2285. // 如果发现歌曲缺少webdav_account_id,立即设置
  2286. queue.forEach((item) => {
  2287. if (!item.webdav_account_id) {
  2288. item.webdav_account_id = this.selectedAccount!.id.toString();
  2289. Logger.info(TAG, `heanup 为歌曲 "${item.name}" 设置webdav_account_id: ${item.webdav_account_id}`);
  2290. }
  2291. });
  2292. }
  2293. const videoItems: VideoItem[] = queue.slice();
  2294. setWebdavPlaylist(videoItems, playIndex);
  2295. Logger.info(TAG, `heanup 保存WebDAV歌曲到全局内存,长度: ${videoItems.length}, 索引: ${playIndex}`);
  2296. void this.playbackController.playQueue(
  2297. videoItems,
  2298. playIndex,
  2299. isJump ? 'controller-open' : 'webdav-main'
  2300. ).then(() => {
  2301. Logger.info(TAG, `heanup WebDAV 直连播放成功,索引: ${playIndex}`);
  2302. }).catch((error: Error) => {
  2303. Logger.error(TAG, `播放歌曲失败: ${error.message}`);
  2304. this.getUIContext().getPromptAction().showToast({ message: '播放失败' });
  2305. });
  2306. } catch (error) {
  2307. const err = error as Error;
  2308. Logger.error(TAG, '播放歌曲失败: ' + err.message);
  2309. this.getUIContext().getPromptAction().showToast({ message: '播放失败' });
  2310. }
  2311. }
  2312. /**
  2313. * 一键创建歌单:将当前WebDAV歌曲全部加入新歌单
  2314. */
  2315. private async createPlaylistFromCurrentWebDav(): Promise<void> {
  2316. try {
  2317. Logger.info(TAG, 'heanup 一键创建歌单开始');
  2318. if (!this.selectedAccount || !this.selectedAccount.id) {
  2319. this.getUIContext().getPromptAction().showToast({ message: `请先选择${getRemoteDriveAccountLabel()}` });
  2320. return;
  2321. }
  2322. if (!this.songs || this.songs.length === 0) {
  2323. // 回退到manager内的歌曲(可能还未复制到页面state)
  2324. this.songs = this.webdavManager.webDavSongs;
  2325. Logger.info(TAG, `heanup 页面songs为空,回退webdavManager.webDavSongs,长度=${this.songs.length}`);
  2326. if (this.songs.length === 0) {
  2327. this.getUIContext().getPromptAction().showToast({ message: '当前目录没有可添加的歌曲' });
  2328. return;
  2329. }
  2330. }
  2331. Logger.info(TAG, `heanup 歌单创建前歌曲数量: ${this.songs.length}`);
  2332. // 确保每首歌都有webdav_account_id
  2333. for (let i = 0; i < this.songs.length; i++) {
  2334. if (!this.songs[i].webdav_account_id) {
  2335. this.songs[i].webdav_account_id = this.selectedAccount.id.toString();
  2336. }
  2337. }
  2338. // 构建歌单名称:账户名 + 当前路径(简化)
  2339. const rawPath = this.currentDirectoryPath || '/';
  2340. const shortPath = rawPath === '/' ? '根目录' : rawPath.replace(/\/$/, '').split('/').slice(-1)[0];
  2341. const playlistName = `${getRemoteDrivePlaylistPrefix(this.selectedAccount.webType)}-${this.selectedAccount.name}-${shortPath}`;
  2342. // 创建歌单
  2343. // 安全获取HostContext
  2344. const uiContext = this.getUIContext();
  2345. const hostCtx = uiContext ? uiContext.getHostContext() : undefined;
  2346. if (!hostCtx) {
  2347. this.getUIContext().getPromptAction().showToast({ message: '无法获取上下文' });
  2348. return;
  2349. }
  2350. const playlistModule = await import('../common/util/PlaylistTable');
  2351. const mediaModule = await import('../common/util/MediaTable');
  2352. const playlistTable = new playlistModule.default(hostCtx);
  2353. const mediaTable = new mediaModule.default(hostCtx);
  2354. // 等待MediaTable底层RDB初始化完成
  2355. await new Promise<void>((resolve) => {
  2356. mediaTable.getRdbStore(hostCtx, () => {
  2357. Logger.info(TAG, 'heanup mediaTable RDB 初始化完成');
  2358. resolve();
  2359. });
  2360. });
  2361. // 先将WebDAV歌曲入库(若不存在)
  2362. let upsertSuccess = 0;
  2363. for (let i = 0; i < this.songs.length; i++) {
  2364. const v = this.songs[i];
  2365. if (!v.id || v.id === '') {
  2366. // 使用filePath作为唯一ID
  2367. v.id = v.filePath;
  2368. }
  2369. if (!v.parentPath) {
  2370. const idxp = v.filePath.lastIndexOf('/');
  2371. if (idxp > 0) {
  2372. v.parentPath = v.filePath.substring(0, idxp);
  2373. }
  2374. }
  2375. const ok = await mediaTable.upsertWebDavVideoItem(v);
  2376. Logger.info(TAG, `heanup upsert 第${i+1}/${this.songs.length}首: ${v.filePath} => ${ok}`);
  2377. if (ok) {
  2378. upsertSuccess++;
  2379. }
  2380. }
  2381. Logger.info(TAG, `heanup WebDAV歌曲入库完成: 成功 ${upsertSuccess}/${this.songs.length}`);
  2382. // 先查询是否已有同名歌单,避免重复创建导致混淆
  2383. const existing = await playlistTable.queryPlaylistByName(playlistName);
  2384. if (existing) {
  2385. this.getUIContext().getPromptAction().showToast({ message: '歌单已存在,直接追加歌曲' });
  2386. const filePathsExist: string[] = this.songs.map(s => s.filePath);
  2387. await playlistTable.addSongsToPlaylist(existing.id, filePathsExist);
  2388. router.pushUrl({ url: 'pages/PlaylistDetailPage', params: { playlist: existing } });
  2389. return;
  2390. }
  2391. Logger.info(TAG, `heanup 准备创建歌单: ${playlistName}`);
  2392. const created = await playlistTable.createPlaylist(playlistName, `来自${getRemoteDriveDisplayLabel(this.selectedAccount.webType)}: ${this.selectedAccount.name} 路径: ${rawPath}`);
  2393. if (!created) {
  2394. this.getUIContext().getPromptAction().showToast({ message: '歌单创建失败' });
  2395. return;
  2396. }
  2397. // 查询刚创建的歌单ID
  2398. const target = await playlistTable.queryPlaylistByName(playlistName);
  2399. if (!target) {
  2400. this.getUIContext().getPromptAction().showToast({ message: '无法找到新建歌单' });
  2401. return;
  2402. }
  2403. // 批量添加歌曲
  2404. const filePaths: string[] = this.songs.map(s => s.filePath);
  2405. Logger.info(TAG, `heanup 开始批量添加歌曲到歌单: ${target.id}`);
  2406. const addResult = await playlistTable.addSongsToPlaylist(target.id, filePaths);
  2407. Logger.info(TAG, `heanup 批量添加结果: ${addResult}`);
  2408. if (!addResult) {
  2409. Logger.warn(TAG, '批量添加歌曲返回false,可能全部已存在或写入失败');
  2410. }
  2411. this.getUIContext().getPromptAction().showToast({ message: `歌单创建成功: ${playlistName}` });
  2412. Logger.info(TAG, `heanup 一键创建歌单成功: ${playlistName}, 添加 ${filePaths.length} 首歌曲`);
  2413. // 跳转到歌单详情页面
  2414. router.pushUrl({ url: 'pages/PlaylistDetailPage', params: { playlist: target } });
  2415. } catch (error) {
  2416. Logger.error(TAG, '一键创建歌单失败: ' + (error as Error).message);
  2417. this.getUIContext().getPromptAction().showToast({ message: '一键创建歌单失败' });
  2418. }
  2419. }
  2420. // 导航到指定层级的面包屑路径
  2421. private async navigateToBreadcrumb(crumb: BreadcrumbItem): Promise<void> {
  2422. if (!crumb) {
  2423. return;
  2424. }
  2425. if (!this.selectedAccount) {
  2426. return
  2427. }
  2428. const targetPath = this.webdavManager.prepareEnterFolderFromPath(crumb.path)
  2429. Logger.info(TAG, `面包屑导航: current=${this.currentDirectoryPath}, target=${targetPath}`)
  2430. this.scheduleDirectoryRefresh(targetPath, () => this.webdavManager.loadFilesInfoFromAccount(this.selectedAccount, targetPath),
  2431. '导航到面包屑路径失败')
  2432. }
  2433. @Builder
  2434. MoreMenuBuilder() {
  2435. Menu() {
  2436. MenuItem({
  2437. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  2438. content: $r('app.string.onekey_add_playlist')
  2439. })
  2440. .onClick(async () => {
  2441. this.createPlaylistFromCurrentWebDav();
  2442. })
  2443. MenuItem({
  2444. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_up_to_line')),
  2445. content: $r('app.string.upload_music_file')
  2446. })
  2447. .onClick(async () => {
  2448. // this.navigateToUploadPage();
  2449. this.isShowUploadFile = !this.isShowUploadFile
  2450. })
  2451. MenuItem({
  2452. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.download')),
  2453. content: '下载中心'
  2454. })
  2455. .onClick(() => {
  2456. this.openDownloadCenter();
  2457. })
  2458. MenuItem({
  2459. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  2460. content: $r('app.string.create_foder')
  2461. })
  2462. .onClick(async () => {
  2463. this.showCreateFolderDialog();
  2464. })
  2465. }.attributeModifier(new MenuModifier())
  2466. }
  2467. @Builder
  2468. SortMenuBuilder() {
  2469. Menu() {
  2470. MenuItem({
  2471. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2472. content: $r('app.string.sort_by_name'),
  2473. symbolEndIcon: this.sortType === 0 ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2474. })
  2475. .backgroundColor(this.getSortItemBackground(0))
  2476. .onClick(async () => {
  2477. this.doSortType(0)
  2478. PreferencesUtil.put("webDavSortType", 0)
  2479. })
  2480. MenuItem({
  2481. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2482. content: '按名称降序',
  2483. symbolEndIcon: this.sortType === 1 ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2484. })
  2485. .backgroundColor(this.getSortItemBackground(1))
  2486. .onClick(async () => {
  2487. this.doSortType(1)
  2488. PreferencesUtil.put("webDavSortType", 1)
  2489. })
  2490. MenuItem({
  2491. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2492. content:'按时间升序',
  2493. symbolEndIcon: this.sortType === 2 ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2494. })
  2495. .backgroundColor(this.getSortItemBackground(2))
  2496. .onClick(async () => {
  2497. this.doSortType(2)
  2498. PreferencesUtil.put("webDavSortType", 2)
  2499. })
  2500. MenuItem({
  2501. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  2502. content: '按时间降序',
  2503. symbolEndIcon: this.sortType === 3 ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2504. })
  2505. .backgroundColor(this.getSortItemBackground(3))
  2506. .onClick(async () => {
  2507. this.doSortType(3)
  2508. PreferencesUtil.put("webDavSortType", 3)
  2509. })
  2510. MenuItem({
  2511. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2512. content:'按大小升序',
  2513. symbolEndIcon: this.sortType === 4 ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2514. })
  2515. .backgroundColor(this.getSortItemBackground(4))
  2516. .onClick(async () => {
  2517. this.doSortType(4)
  2518. PreferencesUtil.put("webDavSortType", 4)
  2519. })
  2520. MenuItem({
  2521. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2522. content: '按大小降序',
  2523. symbolEndIcon: this.sortType === 5 ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2524. })
  2525. .backgroundColor(this.getSortItemBackground(5))
  2526. .onClick(async () => {
  2527. this.doSortType(5)
  2528. PreferencesUtil.put("webDavSortType", 5)
  2529. })
  2530. }.attributeModifier(new MenuModifier())
  2531. }
  2532. private sortSongsForType(target: Array<VideoItem>, index: number): Array<VideoItem> {
  2533. switch (index) {
  2534. case 0:
  2535. Utility.doSortListAscending(target, this.isShowFileName)
  2536. break;
  2537. case 1:
  2538. Utility.doSortListDescending(target, this.isShowFileName)
  2539. break;
  2540. case 2:
  2541. target.sort((a, b) => {
  2542. return a.cTime.localeCompare(b.cTime);
  2543. });
  2544. break;
  2545. case 3:
  2546. target.sort((a, b) => {
  2547. return b.cTime.localeCompare(a.cTime);
  2548. });
  2549. break;
  2550. case 4:
  2551. target.sort((a, b) => {
  2552. return a.videoSize - b.videoSize;
  2553. });
  2554. break;
  2555. case 5:
  2556. target.sort((a, b) => {
  2557. return b.videoSize - a.videoSize;
  2558. });
  2559. break;
  2560. }
  2561. return target;
  2562. }
  2563. private sortFoldersForType(target: Array<FileInfo>, index: number): Array<FileInfo> {
  2564. switch (index) {
  2565. case 0:
  2566. target.sort((a, b) => {
  2567. return a.fileName.localeCompare(b.fileName);
  2568. });
  2569. break;
  2570. case 1:
  2571. target.sort((a, b) => {
  2572. return b.fileName.localeCompare(a.fileName);
  2573. });
  2574. break;
  2575. case 2:
  2576. target.sort((a, b) => {
  2577. return a.time - b.time;
  2578. });
  2579. break;
  2580. case 3:
  2581. target.sort((a, b) => {
  2582. return b.time - a.time;
  2583. });
  2584. break;
  2585. }
  2586. return target;
  2587. }
  2588. doSortType(index: number, shouldScrollToTop: boolean = true) {
  2589. this.sortType = index;
  2590. if (this.isSearchMode && this.searchText.length > 0) {
  2591. if (this.filteredList.length > 0) {
  2592. this.filteredList = this.sortSongsForType([...this.filteredList], index)
  2593. }
  2594. if (this.filteredFolderList.length > 0) {
  2595. this.filteredFolderList = this.sortFoldersForType([...this.filteredFolderList], index)
  2596. }
  2597. this.refreshDisplaySongs(this.filteredList, shouldScrollToTop)
  2598. return
  2599. }
  2600. this.songs = this.sortSongsForType([...this.songs], index)
  2601. this.visibleFoldersState = this.sortFoldersForType([...this.visibleFoldersState], index)
  2602. this.updateListData(this.songs,true, shouldScrollToTop)
  2603. }
  2604. private getSortItemBackground(sortType: number): ResourceColor {
  2605. if (this.sortType !== sortType) {
  2606. return Color.Transparent;
  2607. }
  2608. const isAsc: boolean = sortType % 2 === 0;
  2609. if (isAsc) {
  2610. return this.isDarkMode ? '#295B8A' : '#DCEEFF';
  2611. }
  2612. return this.isDarkMode ? '#7A4D22' : '#FFE9D5';
  2613. }
  2614. @Builder
  2615. topTitleBar(){
  2616. Column() {
  2617. Row({ space: 15 }) {
  2618. if (!this.isSearchMode &&!(this.webdavManager.canGoBack())) {
  2619. //左侧滑动按钮
  2620. TitleBarPointLightButton({
  2621. iconResource: $r('sys.symbol.sort'),
  2622. iconSize: 25,
  2623. pointColor: this.themeColor,
  2624. clickScale: 0.6,
  2625. clickHandler: () => {
  2626. this.getUIContext().animateTo({ duration: 555 }, () => {
  2627. this.isShowDrawer = !this.isShowDrawer
  2628. this.offsetX = 0
  2629. })
  2630. }
  2631. })
  2632. }else{
  2633. //左侧搜索返回按钮
  2634. TitleBarPointLightButton({
  2635. iconResource: $r('sys.symbol.chevron_left'),
  2636. iconSize: 24,
  2637. pointColor: this.themeColor,
  2638. clickScale: 0.6,
  2639. clickHandler: () => {
  2640. if(this.isSearchMode){
  2641. this.isSearchMode = false
  2642. this.searchController.stopEditing()
  2643. this.onSearchInput('')
  2644. }else{
  2645. if(this.webdavManager.canGoBack()){
  2646. this.goBack()
  2647. }
  2648. }
  2649. }
  2650. })
  2651. }
  2652. if(!this.isSearchMode){
  2653. Text(this.selectedAccount.name)
  2654. .margin({left:3,right:10})
  2655. .fontColor($r('app.color.text_color'))
  2656. .fontSize(19)
  2657. .maxLines(1)
  2658. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  2659. .layoutWeight(1)
  2660. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  2661. }
  2662. //搜索框
  2663. Search({ controller: this.searchController,value: this.searchText, placeholder: '输入名称...' })
  2664. .searchButton('搜索',{fontColor:this.themeColor})
  2665. .searchIcon({
  2666. src: $r('sys.media.ohos_ic_public_search_filled')
  2667. })
  2668. .cancelButton({
  2669. style: CancelButtonStyle.CONSTANT,
  2670. icon: {
  2671. src: $r('sys.media.ohos_ic_public_cancel_filled')
  2672. }
  2673. })
  2674. .layoutWeight(1)
  2675. .height(35)
  2676. .maxLength(20)
  2677. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  2678. .placeholderColor(Color.Grey)
  2679. .placeholderFont({ size: 14, weight: 400 })
  2680. .textFont({ size: 14, weight: 400 })
  2681. .onSubmit((value: string) => {
  2682. console.log('onecold onSubmit ='+value)
  2683. this.searchController.stopEditing()
  2684. this.commitSearchHistory(value)
  2685. this.onSearchInput(value);
  2686. })
  2687. .onChange((value: string) => {
  2688. console.log('onecold onChange ='+value)
  2689. this.onSearchInput(value);
  2690. })
  2691. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  2692. .animation({ duration: 300, curve: Curve.Ease })
  2693. //搜索按钮
  2694. if (!this.isSearchMode) {
  2695. TitleBarPointLightButton({
  2696. iconResource: $r('sys.symbol.magnifyingglass'),
  2697. iconSize: 25,
  2698. pointColor: this.themeColor,
  2699. clickScale: 0.6,
  2700. clickHandler: () => {
  2701. this.isSearchMode = true
  2702. this.loadSearchHistory()
  2703. this.restoreCurrentDirectorySearchView()
  2704. void this.webdavManager.ensureGlobalSearchIndex(this.selectedAccount)
  2705. }
  2706. })
  2707. //排序按钮
  2708. TitleBarPointLightButton({
  2709. iconResource: $r('sys.symbol.list_number'),
  2710. iconSize: 25,
  2711. pointColor: this.themeColor,
  2712. clickScale: 0.6,
  2713. menuBuilder: () => {
  2714. this.SortMenuBuilder()
  2715. }
  2716. })
  2717. //添加/上传综合按钮
  2718. TitleBarPointLightButton({
  2719. iconResource: $r('sys.symbol.plus'),
  2720. iconSize: 25,
  2721. pointColor: this.themeColor,
  2722. clickScale: 0.6,
  2723. menuBuilder: () => {
  2724. this.MoreMenuBuilder()
  2725. }
  2726. })
  2727. .bindContentCover($$this.isShowUploadFile, this.UploadFielBuilder(), {
  2728. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2729. })
  2730. }
  2731. }
  2732. }
  2733. .padding({ top: this.topSafeHeight + 10, left: 10, right: 10, bottom: 2 })
  2734. .width('100%')
  2735. }
  2736. @Builder
  2737. UploadFielBuilder() {
  2738. Scroll() {
  2739. Column() {
  2740. UploadMusicPage({
  2741. accountId: this.selectedAccount.id,
  2742. isShowUploadFile:this.isShowUploadFile,
  2743. onResult:(result:boolean)=>{
  2744. console.info("heanup onResult,上传成功,刷新列表")
  2745. if(result){
  2746. // 上传文件成功后刷新当前路径的列表
  2747. if(this.selectedAccount.webType==RemoteDriveType.Baidu){
  2748. ToastUtil.showToast(`由于百度网盘限制,百度网盘的上传路径是apps/${this.appName}`)
  2749. }
  2750. this.refreshFileListAfterUpload()
  2751. }
  2752. },
  2753. })
  2754. }
  2755. }
  2756. .width('100%')
  2757. .height('100%')
  2758. }
  2759. @Builder
  2760. DownloadCenterBuilder() {
  2761. DownloadCenter({
  2762. themeColor: this.themeColor,
  2763. isDarkMode: this.isDarkMode,
  2764. appName: this.appName,
  2765. topSafeHeight: this.topSafeHeight,
  2766. bottomSafeHeight: this.bottomSafeHeight,
  2767. tasksVersion: this.downloadCenterRefreshVersion,
  2768. activeTasksProp: this.downloadCenterActiveTasks,
  2769. completedTasksProp: this.downloadCenterCompletedTasks,
  2770. selectedIndexes: $downloadCenterTabIndex,
  2771. onPauseTask: (taskId: string) => {
  2772. this.pauseDownloadTask(taskId);
  2773. },
  2774. onResumeTask: (taskId: string) => {
  2775. this.resumeDownloadTask(taskId);
  2776. },
  2777. onDeleteTask: (taskId: string) => {
  2778. this.deleteDownloadTask(taskId);
  2779. },
  2780. onPlayCompletedTask: (taskId: string) => {
  2781. this.playCompletedDownloadTask(taskId);
  2782. },
  2783. onClose: () => {
  2784. this.isShowDownloadCenter = false;
  2785. }
  2786. })
  2787. .width('100%')
  2788. .height('100%')
  2789. }
  2790. //搜索功能的实现
  2791. @State searchText: string = ''; // 用户输入内容
  2792. @State filteredList: Array<VideoItem> = []; // 过滤后的歌曲结果
  2793. @State filteredFolderList: Array<FileInfo> = []; // 过滤后的文件夹结果
  2794. @State searchHistoryItems: string[] = [];
  2795. private readonly searchHistoryScope: string = 'webdav_music';
  2796. private loadSearchHistory(): void {
  2797. this.searchHistoryItems = SearchHistoryUtil.load(this.searchHistoryScope);
  2798. }
  2799. private saveSearchHistory(keyword: string): void {
  2800. this.searchHistoryItems = SearchHistoryUtil.save(this.searchHistoryScope, keyword);
  2801. }
  2802. private commitSearchHistory(keyword: string): void {
  2803. const normalized = keyword.trim();
  2804. if (normalized.length === 0) {
  2805. return;
  2806. }
  2807. this.saveSearchHistory(normalized);
  2808. }
  2809. private applySearchHistory(keyword: string): void {
  2810. this.searchText = keyword;
  2811. this.searchController.stopEditing();
  2812. this.onSearchInput(keyword);
  2813. }
  2814. private restoreCurrentDirectorySearchView(shouldScrollToTop: boolean = true): void {
  2815. this.filteredList = []
  2816. this.filteredFolderList = []
  2817. this.songs = this.sortSongsForType([...this.songs], this.sortType)
  2818. this.visibleFoldersState = this.sortFoldersForType([...this.visibleFoldersState], this.sortType)
  2819. this.isSearchLoading = false
  2820. this.refreshDisplaySongs(this.songs, shouldScrollToTop)
  2821. this.syncSelectionAfterRefresh()
  2822. }
  2823. private shouldShowSearchLocation(): boolean {
  2824. return this.isSearchMode && this.searchText.length > 0
  2825. }
  2826. private getSongSearchLocation(song: VideoItem): string {
  2827. if (!this.shouldShowSearchLocation() || !this.selectedAccount) {
  2828. return ''
  2829. }
  2830. return this.webdavManager.getSongSearchLocationLabel(this.selectedAccount, song)
  2831. }
  2832. private getFolderSearchLocation(folder: FileInfo): string {
  2833. if (!this.shouldShowSearchLocation() || !this.selectedAccount) {
  2834. return ''
  2835. }
  2836. return this.webdavManager.getFolderSearchLocationLabel(this.selectedAccount, folder)
  2837. }
  2838. private async applyGlobalSearch(keyword: string, ticket: number): Promise<void> {
  2839. if (!this.selectedAccount) {
  2840. if (ticket === this.searchTicket) {
  2841. this.isSearchLoading = false
  2842. this.filteredList = []
  2843. this.filteredFolderList = []
  2844. this.refreshDisplaySongs([])
  2845. }
  2846. return
  2847. }
  2848. try {
  2849. const result: RemoteDriveGlobalSearchResult = await this.webdavManager.searchGlobalIndex(this.selectedAccount, keyword);
  2850. if (ticket !== this.searchTicket) {
  2851. return
  2852. }
  2853. this.filteredList = this.sortSongsForType([...result.songs], this.sortType)
  2854. this.filteredFolderList = this.sortFoldersForType([...result.folders], this.sortType)
  2855. this.isSearchLoading = result.isIndexing
  2856. this.refreshDisplaySongs(this.filteredList)
  2857. this.syncSelectionAfterRefresh()
  2858. } catch (error) {
  2859. if (ticket !== this.searchTicket) {
  2860. return
  2861. }
  2862. this.isSearchLoading = false
  2863. this.filteredList = []
  2864. this.filteredFolderList = []
  2865. this.refreshDisplaySongs([])
  2866. this.syncSelectionAfterRefresh()
  2867. ToastUtil.showToast(`搜索失败: ${(error as Error).message}`)
  2868. }
  2869. }
  2870. private onSearchInput(value: string) {
  2871. const keyword = value.trim();
  2872. this.searchText = keyword;
  2873. const ticket = ++this.searchTicket;
  2874. if (keyword.length === 0) {
  2875. this.loadSearchHistory();
  2876. this.restoreCurrentDirectorySearchView();
  2877. return;
  2878. }
  2879. if (!this.isSearchMode) {
  2880. this.isSearchMode = true;
  2881. }
  2882. this.isSearchLoading = true;
  2883. void this.applyGlobalSearch(keyword, ticket);
  2884. }
  2885. @Builder
  2886. private SearchHistoryView(): void {
  2887. Column({ space: 10 }) {
  2888. Row() {
  2889. Text('搜索历史')
  2890. .fontSize(14)
  2891. .fontWeight(FontWeight.Medium)
  2892. .fontColor($r('app.color.text_color'))
  2893. Blank()
  2894. Button('清空')
  2895. .fontSize(12)
  2896. .fontColor(this.themeColor)
  2897. .backgroundColor(Color.Transparent)
  2898. .padding({ left: 8, right: 8, top: 4, bottom: 4 })
  2899. .onClick(() => {
  2900. SearchHistoryUtil.clear(this.searchHistoryScope);
  2901. this.searchHistoryItems = [];
  2902. })
  2903. }
  2904. .width('100%')
  2905. Flex({ wrap: FlexWrap.Wrap }) {
  2906. ForEach(this.searchHistoryItems, (keyword: string) => {
  2907. Button(keyword)
  2908. .fontSize(12)
  2909. .fontColor($r('app.color.text_color'))
  2910. .backgroundColor(this.isDarkMode ? '#222222' : '#F2F3F5')
  2911. .borderRadius(16)
  2912. .margin({ right: 8, bottom: 8 })
  2913. .padding({ left: 12, right: 12, top: 8, bottom: 8 })
  2914. .onClick(() => {
  2915. this.applySearchHistory(keyword);
  2916. })
  2917. })
  2918. }
  2919. .width('100%')
  2920. }
  2921. .width('100%')
  2922. .padding({ left: 20, right: 20, top: this.getSearchLoadingTopOffset(), bottom: 10 })
  2923. }
  2924. private openSongPropertySheet(song: VideoItem): void {
  2925. this.songForPropertySheet = song;
  2926. this.isShowSongPropertySheet = true;
  2927. }
  2928. private getSongPropertyValue(value: string | number | undefined): string {
  2929. if (value === undefined) {
  2930. return '--';
  2931. }
  2932. if (typeof value === 'number') {
  2933. return `${value}`;
  2934. }
  2935. if (StrUtil.isEmpty(value)) {
  2936. return '--';
  2937. }
  2938. return value;
  2939. }
  2940. private getSongTypeLabel(song: VideoItem | undefined): string {
  2941. if (!song) {
  2942. return '--';
  2943. }
  2944. if (song.type === CommonConstants.TYPE_LOCAL) {
  2945. return '本地';
  2946. }
  2947. if (song.type === CommonConstants.TYPE_WEBDAV) {
  2948. return 'WebDAV';
  2949. }
  2950. if (song.type === CommonConstants.TYPE_JELLYFIN) {
  2951. return 'Jellyfin';
  2952. }
  2953. if (song.type === CommonConstants.TYPE_EMBY) {
  2954. return 'Emby';
  2955. }
  2956. if (song.type === CommonConstants.TYPE_AUDIOSTATION) {
  2957. return 'AudioStation';
  2958. }
  2959. if (song.type === CommonConstants.TYPE_BAIDU) {
  2960. return '百度网盘';
  2961. }
  2962. if (song.type === CommonConstants.TYPE_NAVIDROME) {
  2963. return 'Navidrome';
  2964. }
  2965. if (song.type === CommonConstants.TYPE_PLEX) {
  2966. return 'Plex';
  2967. }
  2968. return `${song.type}`;
  2969. }
  2970. @Builder
  2971. private SongPropertyRow(label: string, value: string) {
  2972. Column({ space: 4 }) {
  2973. Text(label)
  2974. .fontSize(12)
  2975. .fontColor($r('app.color.index_tab_font_color'))
  2976. .opacity(0.7)
  2977. Text(value)
  2978. .fontSize(14)
  2979. .fontColor($r('app.color.text_color'))
  2980. .maxLines(6)
  2981. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2982. }
  2983. .width('100%')
  2984. .alignItems(HorizontalAlign.Start)
  2985. .padding({ left: 2, right: 2, top: 4, bottom: 4 })
  2986. }
  2987. @Builder
  2988. private SongPropertyCoverRow(label: string, coverPath: string | undefined) {
  2989. Column({ space: 8 }) {
  2990. Text(label)
  2991. .fontSize(12)
  2992. .fontColor($r('app.color.index_tab_font_color'))
  2993. .opacity(0.7)
  2994. if (StrUtil.isNotEmpty(coverPath)) {
  2995. Image(coverPath as string)
  2996. .width(136)
  2997. .height(136)
  2998. .borderRadius(10)
  2999. .sourceSize({ width: 136, height: 136 })
  3000. .objectFit(ImageFit.Cover)
  3001. .alt($r('app.media.alt'))
  3002. .fillColor(this.themeColor)
  3003. } else {
  3004. Text('--')
  3005. .fontSize(14)
  3006. .fontColor($r('app.color.text_color'))
  3007. }
  3008. }
  3009. .width('100%')
  3010. .alignItems(HorizontalAlign.Start)
  3011. .padding({ left: 2, right: 2, top: 4, bottom: 4 })
  3012. }
  3013. @Builder
  3014. private SongPropertyLyricRow(label: string, lyricContent: string | undefined) {
  3015. Column({ space: 4 }) {
  3016. Text(label)
  3017. .fontSize(12)
  3018. .fontColor($r('app.color.index_tab_font_color'))
  3019. .opacity(0.7)
  3020. Text(this.getSongPropertyValue(lyricContent))
  3021. .fontSize(14)
  3022. .fontColor($r('app.color.text_color'))
  3023. .textAlign(TextAlign.Start)
  3024. }
  3025. .width('100%')
  3026. .alignItems(HorizontalAlign.Start)
  3027. .padding({ left: 2, right: 2, top: 4, bottom: 4 })
  3028. }
  3029. @Builder
  3030. private SongPropertySheetBuilder() {
  3031. if (this.songForPropertySheet) {
  3032. Scroll() {
  3033. Column({ space: 10 }) {
  3034. this.SongPropertyCoverRow('音乐封面', this.songForPropertySheet?.pixelMapPath)
  3035. this.SongPropertyRow('歌曲名称', this.getSongPropertyValue(this.songForPropertySheet?.name))
  3036. this.SongPropertyRow('文件名称', this.getSongPropertyValue(this.songForPropertySheet?.fileName))
  3037. this.SongPropertyRow('艺术家', this.getSongPropertyValue(this.songForPropertySheet?.artist))
  3038. this.SongPropertyRow('专辑', this.getSongPropertyValue(this.songForPropertySheet?.album))
  3039. this.SongPropertyRow('时长', this.getSongPropertyValue(this.songForPropertySheet?.duration))
  3040. this.SongPropertyRow('文件大小', this.getSongPropertyValue(this.songForPropertySheet?.size))
  3041. this.SongPropertyRow('比特率', this.getSongPropertyValue(this.songForPropertySheet?.bit_rate))
  3042. this.SongPropertyRow('采样率', this.getSongPropertyValue(this.songForPropertySheet?.sampleRate))
  3043. this.SongPropertyLyricRow('内嵌歌词', this.songForPropertySheet?.lyricContent)
  3044. this.SongPropertyRow('创建时间', this.getSongPropertyValue(this.songForPropertySheet?.cTime))
  3045. this.SongPropertyRow('来源类型', this.getSongTypeLabel(this.songForPropertySheet))
  3046. this.SongPropertyRow('文件路径', this.getSongPropertyValue(this.songForPropertySheet?.filePath))
  3047. }
  3048. .width('100%')
  3049. .padding({ left: 12, right: 12, top: 8, bottom: 12 })
  3050. }
  3051. .width('100%')
  3052. .height('100%')
  3053. .scrollBar(BarState.Auto)
  3054. } else {
  3055. Column() {
  3056. Text('暂无歌曲属性信息')
  3057. .fontSize(14)
  3058. .fontColor($r('app.color.text_color'))
  3059. .opacity(0.65)
  3060. }
  3061. .width('100%')
  3062. .height('100%')
  3063. .justifyContent(FlexAlign.Center)
  3064. .alignItems(HorizontalAlign.Center)
  3065. }
  3066. }
  3067. build() {
  3068. Stack() {
  3069. if (this.accounts.length === 0) {
  3070. this.buildEmptyView();
  3071. } else {
  3072. this.buildContentView();
  3073. }
  3074. // 顶部区域:标题栏在上,面包屑在下
  3075. Column() {
  3076. this.topTitleBar()
  3077. this.breaker()
  3078. }
  3079. .width('100%')
  3080. .visibility(this.isShowTitleBar?Visibility.Visible:
  3081. this.autoHideTitle?Visibility.None:Visibility.Visible)
  3082. .animation({
  3083. duration: 500,
  3084. curve: Curve.Friction // 可选动画曲线
  3085. })
  3086. .position({ top: 0, left: 0 })
  3087. // .backgroundColor($r('app.color.start_window_background'))
  3088. // 多选操作条,位于播放条之上(仅在多选模式下显示)
  3089. if (this.isMultiSelect || this.isDeletingSelection) {
  3090. this.buildSelectionOverlay()
  3091. }
  3092. }
  3093. .width('100%')
  3094. .height('100%')
  3095. .alignContent(Alignment.Bottom)
  3096. .backgroundImage(this.isMusicCoverHomeBackgroundActive()
  3097. ? this.customizeMusicBgPath
  3098. : (this.isCustomizeBg ? this.customizeBgPath : $r('app.color.start_window_background')))
  3099. .backgroundImageSize(this.isLandscape?{width:'100%'}:{ height: '100%'})
  3100. .backgroundImagePosition(Alignment.Center)
  3101. .backdropBlur(this.blurValue)
  3102. .backgroundBrightness({rate:this.isMusicCoverHomeBackgroundActive() || this.isCustomizeBg ? 0.1 : 0,
  3103. lightUpDegree:this.bgBrightness})
  3104. .backgroundBlurStyle(this.isMusicCoverHomeBackgroundActive()
  3105. ? BlurStyle.BACKGROUND_ULTRA_THICK :
  3106. BlurStyle.NONE)
  3107. .bindSheet($$this.isShowSongPropertySheet, this.SongPropertySheetBuilder(), {
  3108. height: '99%',
  3109. dragBar: true,
  3110. showClose: true,
  3111. preferType: SheetType.CENTER,
  3112. blurStyle: BlurStyle.Thin,
  3113. title: { title: '歌曲属性' }
  3114. })
  3115. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  3116. }
  3117. private getSearchLoadingTopOffset(): number {
  3118. return this.topSafeHeight + (this.currentDirectoryPath !== '' ? 100 : 56)
  3119. }
  3120. private shouldShowSearchIndexingTip(): boolean {
  3121. return this.isSearchMode && this.searchText.length > 0 && this.isSearchLoading
  3122. }
  3123. private getListContentStartOffset(): number {
  3124. if (this.shouldShowSearchIndexingTip()) {
  3125. return 8
  3126. }
  3127. if(this.isLoading)
  3128. return 8
  3129. return this.topSafeHeight + 85
  3130. }
  3131. // 目录切换时统一在当前可见的账户图标外层显示转圈,避免页面中间闪大 loading。
  3132. @Builder
  3133. private buildDirectoryNavigationIndicator(iconSize: number, containerSize: number) {
  3134. Stack({ alignContent: Alignment.Center }) {
  3135. if (this.isDirectoryNavigationLoading) {
  3136. // 使用环形进度外圈承载目录切换态,避免在标题栏或页面中央再出现第二套 loading。
  3137. Progress({ value: 0, total: 100, type: ProgressType.Ring })
  3138. .width(containerSize + 8)
  3139. .height(containerSize + 8)
  3140. .color(this.themeColor)
  3141. .style({ strokeWidth: 2.5, status: ProgressStatus.LOADING, shadow: false })
  3142. .scale({ x: -1, y: 1 })
  3143. }
  3144. Image(this.selectedAccount.coverPath ?
  3145. this.selectedAccount.coverPath : getCloudDiskIcon(this.selectedAccount.webType))
  3146. .width(iconSize)
  3147. .height(iconSize)
  3148. .alt($r('app.media.cloudDisk'))
  3149. }
  3150. .width(containerSize)
  3151. .height(containerSize)
  3152. .borderRadius(containerSize / 2)
  3153. .backgroundColor('#EFEFEF')
  3154. }
  3155. @Builder
  3156. breaker() {
  3157. // 面包屑导航
  3158. Column({ space: 8 }) {
  3159. if (!this.isSearchMode || this.webdavManager.canGoBack()) {
  3160. Row({ space: 8 }) {
  3161. // 根目录只展示账号图标和加载态,不再承载返回动作;子目录才点击返回上级。
  3162. if (this.webdavManager.canGoBack()) {
  3163. Row() {
  3164. this.buildDirectoryNavigationIndicator(18, 24)
  3165. }
  3166. .width(24)
  3167. .height(24)
  3168. .margin({left:5})
  3169. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.92 })
  3170. .onClick(() => this.goBack())
  3171. .bindContentCover($$this.isShowDownloadCenter, this.DownloadCenterBuilder(),
  3172. {
  3173. modalTransition:ModalTransition.DEFAULT,
  3174. onWillDisappear: () => {
  3175. this.isShowDownloadCenter = false
  3176. },
  3177. })
  3178. } else {
  3179. Row() {
  3180. this.buildDirectoryNavigationIndicator(18, 24)
  3181. }
  3182. .width(24)
  3183. .height(24)
  3184. .margin({left:5})
  3185. .bindContentCover($$this.isShowDownloadCenter, this.DownloadCenterBuilder(),
  3186. {
  3187. modalTransition:ModalTransition.DEFAULT,
  3188. onWillDisappear: () => {
  3189. this.isShowDownloadCenter = false
  3190. },
  3191. })
  3192. }
  3193. Row({ space: 4 }) {
  3194. if (this.breadcrumbs.length === 0) {
  3195. Text('根目录')
  3196. .fontSize(15)
  3197. .fontColor($r('app.color.text_color'))
  3198. .maxLines(1)
  3199. .textOverflow({ overflow: TextOverflow.Ellipsis })
  3200. } else {
  3201. ForEach(this.breadcrumbs, (crumb: BreadcrumbItem, index: number) => {
  3202. Row() {
  3203. Text(crumb.label)
  3204. .fontSize(15)
  3205. .fontColor($r('app.color.text_color'))
  3206. .maxLines(1)
  3207. .textOverflow({ overflow: TextOverflow.Ellipsis })
  3208. }
  3209. .onClick(() => {
  3210. this.navigateToBreadcrumb(crumb);
  3211. })
  3212. // 添加分隔符(除了最后一个元素)
  3213. if (index < this.breadcrumbs.length - 1) {
  3214. Text('/')
  3215. .fontSize(15)
  3216. .fontColor($r('app.color.index_tab_font_color'))
  3217. .opacity(0.6)
  3218. }
  3219. })
  3220. }
  3221. }
  3222. .layoutWeight(1)
  3223. }
  3224. .width('100%')
  3225. .padding({ left: 4, right: 4 })
  3226. }
  3227. }
  3228. .width('100%')
  3229. .padding({ left: 12, right: 12, top: 8, bottom: 5 })
  3230. }
  3231. // 空状态视图
  3232. @Builder
  3233. buildEmptyView() {
  3234. Column({ space: 20 }) {
  3235. Image($r('app.media.cloudDisk'))
  3236. .width(120)
  3237. .height(120)
  3238. .opacity(0.3)
  3239. Text(`暂无${getRemoteDriveAccountLabel()}`)
  3240. .fontSize(16)
  3241. .fontColor($r('app.color.index_tab_font_color'))
  3242. .opacity(0.6)
  3243. }
  3244. .justifyContent(FlexAlign.Center)
  3245. .width('100%')
  3246. .height('100%')
  3247. }
  3248. // 内容视图
  3249. @Builder
  3250. buildContentView() {
  3251. Column() {
  3252. // 加载状态
  3253. Row() {
  3254. LoadingProgress()
  3255. .width(30)
  3256. .height(30)
  3257. .color(this.themeColor)
  3258. Text('加载中...')
  3259. .fontSize(14)
  3260. .fontColor($r('app.color.index_tab_font_color'))
  3261. .margin({ left: 12 })
  3262. }
  3263. .padding({top: this.topSafeHeight + 90, left: 20, right: 20})
  3264. .visibility(this.isLoading?Visibility.Visible:Visibility.None)
  3265. .opacity(this.isLoading ? 1 : 0)
  3266. .animation({
  3267. duration: 800,
  3268. curve: Curve.Smooth // 可选动画曲线
  3269. })
  3270. if (this.shouldShowSearchIndexingTip()) {
  3271. Row({ space: 8 }) {
  3272. LoadingProgress()
  3273. .width(18)
  3274. .height(18)
  3275. .color(this.themeColor)
  3276. Text('正在构建全局索引,结果会持续补全')
  3277. .fontSize(12)
  3278. .fontColor($r('app.color.index_tab_font_color'))
  3279. .opacity(0.65)
  3280. }
  3281. .alignSelf(ItemAlign.Center)
  3282. .padding({ left: 20, right: 20, top: this.getSearchLoadingTopOffset() })
  3283. }
  3284. // 文件列表(文件夹 + 歌曲)
  3285. if ((this.isSearchMode ? this.filteredFolderList.length : this.visibleFoldersState.length) > 0 ||
  3286. this.dataSource.totalCount() > 0) {
  3287. List({ scroller: this.listScroller ,space: 0 }) {
  3288. // 显示文件夹 - 只显示当前目录下的直接子文件夹
  3289. ForEach(this.isSearchMode ? this.filteredFolderList : this.visibleFoldersState, (folder: FileInfo) => {
  3290. if (this.isMultiSelect) {
  3291. ListItem() {
  3292. this.buildFolderItem(folder)
  3293. }
  3294. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  3295. } else {
  3296. ListItem() {
  3297. this.buildFolderItem(folder)
  3298. }
  3299. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  3300. .swipeAction({
  3301. end: this.buildSwipeDeleteAction(() => {
  3302. this.confirmDeleteSingleFolder(folder)
  3303. }),
  3304. edgeEffect: SwipeEdgeEffect.None
  3305. })
  3306. }
  3307. }, (folder: FileInfo) => folder.name+folder.fileName)
  3308. // 显示歌曲
  3309. LazyForEach(this.dataSource, (song: VideoItem, index: number) => {
  3310. if (this.isMultiSelect) {
  3311. ListItem() {
  3312. this.buildSongItem(song, index)
  3313. }
  3314. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  3315. } else {
  3316. ListItem() {
  3317. this.buildSongItem(song, index)
  3318. }
  3319. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  3320. .swipeAction({
  3321. end: this.buildSwipeDeleteAction(() => {
  3322. this.confirmDeleteSingleSong(song)
  3323. }),
  3324. edgeEffect: SwipeEdgeEffect.None
  3325. })
  3326. }
  3327. }, (item: VideoItem, index: number) => {
  3328. return buildWebDavSongItemRenderKey(item.filePath, index, item.pixelMapPath)
  3329. })
  3330. }
  3331. .scrollBar(BarState.Off)
  3332. .onScrollIndex((start: number, end: number) => {
  3333. this.updateVisibleRemoteThumbRange(start, end)
  3334. })
  3335. .onScrollFrameBegin((offset: number) => {
  3336. // 获取当前滚动偏移量
  3337. if(this.autoHideTitle){
  3338. const currentOffsetY = this.listScroller.currentOffset().yOffset;
  3339. // 判断滚动方向
  3340. if (currentOffsetY > this.prevOffsetY) {
  3341. this.isShowTitleBar = false
  3342. } else if (currentOffsetY < this.prevOffsetY) {
  3343. this.isShowTitleBar = true
  3344. }
  3345. // 更新前一次偏移量
  3346. this.prevOffsetY = currentOffsetY;
  3347. }
  3348. return { offsetRemain: offset };
  3349. })
  3350. .contentStartOffset(this.getListContentStartOffset())
  3351. .contentEndOffset(this.bottomSafeHeight+70)
  3352. .layoutWeight(1)
  3353. .margin({ top: 4 })
  3354. } else if (this.isSearchMode && this.searchText.length === 0 && this.searchHistoryItems.length > 0) {
  3355. this.SearchHistoryView()
  3356. } else if (!this.isLoading) {
  3357. Column() {
  3358. Text(this.isSearchMode && this.searchText.length > 0 ? '没有找到匹配结果' : '暂无内容')
  3359. .fontSize(14)
  3360. .fontColor($r('app.color.index_tab_font_color'))
  3361. .opacity(0.6)
  3362. Text(this.isSearchMode && this.searchText.length > 0 ?
  3363. (this.isSearchLoading ? '正在继续扫描更多目录...' : '可以换个关键词再试') :
  3364. '点击"左侧菜单"网盘加载')
  3365. .fontSize(12)
  3366. .fontColor($r('app.color.index_tab_font_color'))
  3367. .opacity(0.4)
  3368. .margin({ top: 8 })
  3369. }
  3370. .justifyContent(FlexAlign.Center)
  3371. .layoutWeight(1)
  3372. }
  3373. }
  3374. .layoutWeight(1)
  3375. }
  3376. @Builder
  3377. private buildMultiSelectBar() {
  3378. Row({ space: 12 }) {
  3379. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  3380. .width(55)
  3381. .height(55)
  3382. .fontSize(13)
  3383. .backgroundColor(this.themeColor)
  3384. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3385. .onClick(() => this.toggleSelectAll())
  3386. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  3387. .width(55)
  3388. .height(55)
  3389. .fontSize(13)
  3390. .backgroundColor(this.themeColor)
  3391. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3392. .enabled(this.getSelectedEntryCount() > 0 && !this.isDeletingSelection)
  3393. .onClick(() => this.confirmDeleteSelected())
  3394. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  3395. .width(55)
  3396. .height(55)
  3397. .fontSize(13)
  3398. .backgroundColor(this.themeColor)
  3399. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3400. .enabled(this.canOperateOnSelectedSongs())
  3401. .onClick(() => {
  3402. void this.openSelectedSongsAddToPlaylistDialog();
  3403. })
  3404. Button('下载', { type: ButtonType.Circle, stateEffect: true })
  3405. .width(55)
  3406. .height(55)
  3407. .fontSize(13)
  3408. .backgroundColor(this.themeColor)
  3409. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3410. .enabled(this.canOperateOnSelectedSongs())
  3411. .onClick(() => {
  3412. void this.enqueueSelectedSongsDownload();
  3413. })
  3414. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  3415. .width(55)
  3416. .height(55)
  3417. .fontSize(13)
  3418. .backgroundColor(this.themeColor)
  3419. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3420. .onClick(() => this.exitMultiSelect())
  3421. }
  3422. .width('100%')
  3423. .padding({ bottom: 10, top: 12 })
  3424. .justifyContent(FlexAlign.Center)
  3425. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  3426. .opacity(this.isMultiSelect ? 1 : 0)
  3427. .animation({ duration: 300, curve: 'ease-in-out' })
  3428. }
  3429. @Builder
  3430. private buildSelectionOverlay() {
  3431. Column() {
  3432. Row({ space: 10 }) {
  3433. LoadingProgress()
  3434. .width(22)
  3435. .height(22)
  3436. .color(this.themeColor)
  3437. Text('正在删除...')
  3438. .fontSize(14)
  3439. .fontColor($r('app.color.index_tab_font_color'))
  3440. }
  3441. .padding({ top: 12, bottom: 6 })
  3442. .justifyContent(FlexAlign.Center)
  3443. .visibility(this.isDeletingSelection ? Visibility.Visible : Visibility.None)
  3444. this.buildMultiSelectBar()
  3445. }
  3446. .width('100%')
  3447. .padding({ left: 12, right: 12, bottom: this.bottomSafeHeight })
  3448. }
  3449. private getPointLightItemKey(prefix: string, value: string): string {
  3450. return `${prefix}_${value}`
  3451. }
  3452. private handlePointLightTouch(itemKey: string, event: TouchEvent): void {
  3453. if (deviceInfo.sdkApiVersion < 20) {
  3454. return
  3455. }
  3456. if (event.type === TouchType.Down) {
  3457. this.activePointLightItemKey = itemKey
  3458. this.pointLightOptions = {
  3459. color: this.themeColor,
  3460. intensity: 1,
  3461. height: 60
  3462. }
  3463. return
  3464. }
  3465. if ((event.type === TouchType.Up || event.type === TouchType.Cancel) && this.activePointLightItemKey === itemKey) {
  3466. this.activePointLightItemKey = ''
  3467. this.pointLightOptions = undefined
  3468. }
  3469. }
  3470. private getPointLightOptions(itemKey: string): hdsEffect.PointLightOptions | undefined {
  3471. if (this.activePointLightItemKey !== itemKey) {
  3472. return undefined
  3473. }
  3474. return this.pointLightOptions
  3475. }
  3476. // 文件夹列表项
  3477. @Builder
  3478. buildFolderItem(folder: FileInfo) {
  3479. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  3480. Row({ space: 2 }) {
  3481. SymbolGlyph($r('sys.symbol.folder'))
  3482. .fontSize(48)
  3483. .fontColor([this.themeColor])
  3484. .alignSelf(ItemAlign.Center)
  3485. .margin({ left: 8, right: 6 })
  3486. // 文件夹信息
  3487. Column({ space: 4 }) {
  3488. Text(decodeUrlEncodedString(folder.fileName.replace(/\/+$/, '')))
  3489. .fontSize(15)
  3490. .fontColor($r('app.color.index_tab_font_color'))
  3491. .maxLines(1)
  3492. .textOverflow({ overflow: TextOverflow.Ellipsis })
  3493. Text(this.getFolderSearchLocation(folder))
  3494. .fontSize(12)
  3495. .fontColor($r('app.color.index_tab_font_color'))
  3496. .opacity(0.48)
  3497. .maxLines(1)
  3498. .textOverflow({ overflow: TextOverflow.Ellipsis })
  3499. .visibility(this.getFolderSearchLocation(folder).length > 0 ? Visibility.Visible : Visibility.None)
  3500. Text('文件夹')
  3501. .fontSize(13)
  3502. .fontColor($r('app.color.index_tab_font_color'))
  3503. .opacity(0.6)
  3504. }
  3505. .alignItems(HorizontalAlign.Start)
  3506. .layoutWeight(1)
  3507. Checkbox({ name: `folder_checkbox_${this.resolveFolderSelectionKey(folder)}` })
  3508. .select(this.isFolderSelected(folder))
  3509. .selectedColor(this.themeColor)
  3510. .opacity(this.isMultiSelect ? 1 : 0)
  3511. .animation({
  3512. duration: 300,
  3513. curve: 'Smooth'
  3514. })
  3515. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  3516. .onChange((checked: boolean) => this.handleFolderCheckboxSelection(folder, checked))
  3517. .margin({ left: 10, top: 8, bottom: 8, right: 12 })
  3518. .width(22)
  3519. .height(22)
  3520. }
  3521. }
  3522. .reuseId('dir_item')
  3523. .width('100%')
  3524. .padding(12)
  3525. .backgroundColor(Color.Transparent)
  3526. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.8 })
  3527. .onClick(() => {
  3528. if (this.ignoreTapAfterExitMultiSelect) {
  3529. return;
  3530. }
  3531. if (this.isMultiSelect) {
  3532. this.toggleFolderSelection(folder);
  3533. return;
  3534. }
  3535. if (this.isSearchMode && this.searchText.length > 0) {
  3536. this.isSearchMode = false
  3537. this.searchController.stopEditing()
  3538. this.onSearchInput('')
  3539. }
  3540. this.enterFolder(folder);
  3541. this.breadcrumbs = this.webdavManager.getBreadcrumbs();
  3542. })
  3543. .bindContextMenu(this.FolderLongPressMenuBuilder(folder), ResponseType.LongPress,
  3544. {
  3545. preview: MenuPreviewMode.IMAGE
  3546. })
  3547. .bindContextMenu(this.FolderLongPressMenuBuilder(folder), ResponseType.RightClick,
  3548. {
  3549. preview: MenuPreviewMode.IMAGE
  3550. })
  3551. .onTouch((event: TouchEvent) => {
  3552. this.handlePointLightTouch(this.getPointLightItemKey('webdav_folder', folder.href), event)
  3553. })
  3554. .visualEffect(deviceInfo.sdkApiVersion >= 20
  3555. ? new hdsEffect.HdsEffectBuilder()
  3556. .pointLight({
  3557. options: this.getPointLightOptions(this.getPointLightItemKey('webdav_folder', folder.href)),
  3558. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  3559. })
  3560. .buildEffect()
  3561. : undefined)
  3562. }
  3563. // 歌曲列表项
  3564. @Builder
  3565. buildSongItem(song: VideoItem, index: number) {
  3566. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  3567. Row({ space: 12 }) {
  3568. // 序号
  3569. // 歌曲封面
  3570. Image(song.pixelMapPath ? song.pixelMapPath : $r('app.media.alt'))
  3571. .width(52)
  3572. .height(52)
  3573. .borderRadius(9)
  3574. .sourceSize({width:38, height:38})
  3575. .alt($r('app.media.alt'))
  3576. .fillColor(this.themeColor)
  3577. .objectFit(ImageFit.Cover)
  3578. .shadow({
  3579. radius: StrUtil.isEmpty(song.pixelMapPath) ?6:14,
  3580. type: ShadowType.BLUR,
  3581. color: 'on_primary'
  3582. })
  3583. .margin({ left: 8 })
  3584. .onClick(() => {
  3585. if (this.isMultiSelect) {
  3586. this.toggleSongSelection(song);
  3587. } else {
  3588. this.playSong(song, index, true);
  3589. }
  3590. })
  3591. // 歌曲信息
  3592. Column({ space: 4 }) {
  3593. Text(this.isShowFileName?song.fileName :song.name)
  3594. .fontSize(15)
  3595. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3596. .fontColor(this.currentSong?.filePath==song.filePath?this.themeColor:$r('app.color.index_tab_font_color'))
  3597. .maxLines(1)
  3598. .textOverflow({ overflow: TextOverflow.Ellipsis })
  3599. Row(){
  3600. if (StrUtil.isNotEmpty(song.md5Str)) {
  3601. Text(this.buildSongQualityLabel(song))
  3602. .fontSize(10)
  3603. .fontColor($r('app.color.index_tab_font_color'))
  3604. .fontWeight(500)
  3605. .padding({ top: 2, right: 5, left: 5, bottom: 2 })
  3606. .borderRadius(6)
  3607. .margin({right:3})
  3608. .backgroundColor('#FFC107')
  3609. .opacity(0.92)
  3610. }
  3611. Text((song.artist ?? '') + " ")
  3612. .fontSize(13)
  3613. .fontColor(this.currentSong?.filePath==song.filePath?this.themeColor:$r('app.color.index_tab_font_color'))
  3614. .opacity(0.6)
  3615. .maxLines(1)
  3616. .visibility(song.artist?Visibility.Visible:Visibility.None)
  3617. .textOverflow({ overflow: TextOverflow.Ellipsis })
  3618. Text(this.buildSongMetaLine(song))
  3619. .fontSize(13)
  3620. .fontColor(this.currentSong?.filePath==song.filePath?this.themeColor:
  3621. $r('app.color.index_tab_font_color'))
  3622. .opacity(0.6)
  3623. .maxLines(1)
  3624. .textOverflow({ overflow: TextOverflow.Ellipsis })
  3625. }
  3626. .width('90%')
  3627. Text(this.getSongSearchLocation(song))
  3628. .fontSize(12)
  3629. .fontColor(this.currentSong?.filePath==song.filePath?this.themeColor:$r('app.color.index_tab_font_color'))
  3630. .opacity(0.42)
  3631. .maxLines(1)
  3632. .textOverflow({ overflow: TextOverflow.Ellipsis })
  3633. .visibility(this.getSongSearchLocation(song).length > 0 ? Visibility.Visible : Visibility.None)
  3634. }
  3635. .alignItems(HorizontalAlign.Start)
  3636. .layoutWeight(1)
  3637. .padding({ right: 20 })
  3638. Column() {
  3639. Checkbox({ name: 'checkbox_' + index })
  3640. .select(this.isSongSelected(song))
  3641. .selectedColor(this.themeColor)
  3642. .opacity(this.isMultiSelect ? 1 : 0)
  3643. .animation({
  3644. duration: 300,
  3645. curve: 'Smooth'
  3646. })
  3647. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  3648. .onChange((checked: boolean) => this.handleCheckboxSelection(song, checked))
  3649. .margin({ left: 10, top: 8, bottom: 8, right: 12 })
  3650. .width(22)
  3651. .height(22)
  3652. PlayingIndicator({
  3653. isActive: this.currentSong?.filePath == song.filePath && !this.isMultiSelect,
  3654. indicatorSize: 18,
  3655. marginRight: 12,
  3656. marginTop: 8,
  3657. marginBottom: 8
  3658. })
  3659. }
  3660. }
  3661. }
  3662. .width('100%')
  3663. .padding(12)
  3664. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.8 })
  3665. .backgroundColor(Color.Transparent)
  3666. .onClick(() => {
  3667. if (this.ignoreTapAfterExitMultiSelect) {
  3668. return;
  3669. }
  3670. if (this.isMultiSelect) {
  3671. this.toggleSongSelection(song);
  3672. } else {
  3673. this.playSong(song, index);
  3674. }
  3675. })
  3676. // .gesture(LongPressGesture().onAction(() => {
  3677. // this.enterMultiSelect(song);
  3678. // }))
  3679. .bindContextMenu(this.LongPressMenuBuilder(song), ResponseType.LongPress,
  3680. {
  3681. preview: MenuPreviewMode.IMAGE
  3682. })
  3683. .bindContextMenu(this.LongPressMenuBuilder(song), ResponseType.RightClick,
  3684. {
  3685. preview: MenuPreviewMode.IMAGE
  3686. })
  3687. .onTouch((event: TouchEvent) => {
  3688. this.handlePointLightTouch(this.getPointLightItemKey('webdav_song', song.filePath), event)
  3689. })
  3690. .visualEffect(deviceInfo.sdkApiVersion >= 20
  3691. ? new hdsEffect.HdsEffectBuilder()
  3692. .pointLight({
  3693. options: this.getPointLightOptions(this.getPointLightItemKey('webdav_song', song.filePath)),
  3694. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  3695. })
  3696. .buildEffect()
  3697. : undefined)
  3698. }
  3699. @Builder
  3700. LongPressMenuBuilder(song: VideoItem) {
  3701. Scroll() {
  3702. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  3703. Menu() {
  3704. MenuItem({
  3705. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  3706. content: '下一首播放'
  3707. })
  3708. .onClick(() => {
  3709. this.addSongToNextPlay(song);
  3710. })
  3711. MenuItem({
  3712. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  3713. content: '添加到歌单'
  3714. })
  3715. .onClick(async () => {
  3716. await this.openSongAddToPlaylistDialog(song);
  3717. })
  3718. //多选
  3719. MenuItem({
  3720. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  3721. content: $r('app.string.select_all')
  3722. })
  3723. .onClick(() => {
  3724. this.enterMultiSelect(song);
  3725. })
  3726. //下载
  3727. MenuItem({
  3728. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.download')),
  3729. content: '下载'
  3730. })
  3731. .onClick(async () => {
  3732. await this.enqueueSongDownload(song);
  3733. })
  3734. MenuItem({
  3735. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  3736. content: '重命名'
  3737. })
  3738. .visibility(this.canRenameRemoteSong(song) ? Visibility.Visible : Visibility.None)
  3739. .onClick(() => {
  3740. this.showRenameSongDialog(song);
  3741. })
  3742. //属性
  3743. MenuItem({
  3744. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  3745. content: '属性'
  3746. })
  3747. .onClick(() => {
  3748. this.openSongPropertySheet(song);
  3749. })
  3750. //删除
  3751. MenuItem({
  3752. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  3753. content: $r('app.string.delete')
  3754. })
  3755. .onClick(() => {
  3756. this.confirmDeleteSingleSong(song);
  3757. })
  3758. }
  3759. .font({ size: 14, weight: FontWeight.Normal })
  3760. }
  3761. .width(180)
  3762. }
  3763. .height('auto')
  3764. .enableScrollInteraction(true)
  3765. .scrollBar(BarState.Off)
  3766. }
  3767. @Builder
  3768. FolderLongPressMenuBuilder(folder: FileInfo) {
  3769. Scroll() {
  3770. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  3771. Menu() {
  3772. MenuItem({
  3773. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  3774. content: $r('app.string.select_all')
  3775. })
  3776. .onClick(() => {
  3777. this.enterFolderMultiSelect(folder);
  3778. })
  3779. MenuItem({
  3780. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  3781. content: '重命名'
  3782. })
  3783. .visibility(this.canRenameRemoteFolder() ? Visibility.Visible : Visibility.None)
  3784. .onClick(() => {
  3785. this.showRenameFolderDialog(folder);
  3786. })
  3787. MenuItem({
  3788. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  3789. content: $r('app.string.delete')
  3790. })
  3791. .onClick(() => {
  3792. this.confirmDeleteSingleFolder(folder);
  3793. })
  3794. }
  3795. .font({ size: 14, weight: FontWeight.Normal })
  3796. }
  3797. .width(180)
  3798. }
  3799. .height('auto')
  3800. .enableScrollInteraction(true)
  3801. .scrollBar(BarState.Off)
  3802. }
  3803. // 对话框控制器
  3804. private createFolderDialogController: CustomDialogController | null = null;
  3805. private renameSongDialogController: CustomDialogController | null = null;
  3806. /**
  3807. * 显示创建文件夹对话框
  3808. */
  3809. private showCreateFolderDialog(): void {
  3810. if (!this.selectedAccount) {
  3811. this.getUIContext().getPromptAction().showToast({ message: `请先选择${getRemoteDriveAccountLabel()}` });
  3812. return;
  3813. }
  3814. // 获取当前主题色
  3815. const currentThemeColor = this.themeColor;
  3816. // 创建自定义对话框
  3817. this.createFolderDialogController = new CustomDialogController({
  3818. builder: CreateFolderDialog({
  3819. onConfirm: (folderName: string) => {
  3820. if (folderName.trim().length > 0) {
  3821. void this.createFolder(folderName.trim());
  3822. } else {
  3823. this.getUIContext().getPromptAction().showToast({ message: '文件夹名称不能为空' });
  3824. }
  3825. },
  3826. onCancel: () => {
  3827. // 用户取消创建
  3828. },
  3829. initialName: '',
  3830. themeColor: currentThemeColor
  3831. }),
  3832. autoCancel: true,
  3833. alignment: DialogAlignment.Center,
  3834. customStyle: false
  3835. });
  3836. this.createFolderDialogController.open();
  3837. }
  3838. /**
  3839. * 上传成功后刷新文件列表
  3840. */
  3841. private async refreshFileListAfterUpload(): Promise<void> {
  3842. if (!this.selectedAccount) {
  3843. Logger.warn(TAG, '刷新失败:未选择账户');
  3844. return;
  3845. }
  3846. try {
  3847. Logger.info(TAG, 'heanup 开始刷新上传后的文件列表');
  3848. // 显示加载状态
  3849. this.isLoading = true;
  3850. // 重新加载当前账户的文件信息
  3851. await this.webdavManager.loadFilesInfoFromAccount(this.selectedAccount,
  3852. this.currentDirectoryPath || this.selectedAccount.filepath || '/');
  3853. Logger.info(TAG, 'heanup 文件列表刷新完成');
  3854. } catch (error) {
  3855. const err = error as Error;
  3856. Logger.error(TAG, `heanup 刷新文件列表失败: ${err.message}`);
  3857. // 显示错误提示
  3858. this.getUIContext().getPromptAction().showToast({
  3859. message: `刷新失败: ${err.message}`
  3860. });
  3861. } finally {
  3862. this.isLoading = false;
  3863. }
  3864. }
  3865. /**
  3866. * 创建文件夹的实际方法
  3867. * @param folderName 文件夹名称
  3868. */
  3869. private async createFolder(folderName: string): Promise<void> {
  3870. if (!this.selectedAccount) {
  3871. this.getUIContext().getPromptAction().showToast({ message: `请先选择${getRemoteDriveAccountLabel()}` });
  3872. return;
  3873. }
  3874. if (folderName.length === 0) {
  3875. this.getUIContext().getPromptAction().showToast({ message: '文件夹名称不能为空' });
  3876. return;
  3877. }
  3878. try {
  3879. Logger.info(TAG, `heanup 开始创建文件夹: ${folderName}`);
  3880. // 显示加载状态
  3881. this.isLoading = true;
  3882. if(this.selectedAccount.webType==RemoteDriveType.Baidu){
  3883. // 调用RemoteDriveManager的createBaiduFolder方法
  3884. await this.webdavManager.createBaiduFolder(this.selectedAccount, folderName);
  3885. }else if(this.selectedAccount.webType==RemoteDriveType.WebDav){
  3886. // 调用RemoteDriveManager的createWebDavFolder方法
  3887. await this.webdavManager.createWebDavFolder(this.selectedAccount, folderName);
  3888. }else if(this.selectedAccount.webType==RemoteDriveType.Smb){
  3889. // 调用RemoteDriveManager的createSMBFolder方法
  3890. await this.webdavManager.createSMBFolder(this.selectedAccount, folderName);
  3891. }else if(this.selectedAccount.webType==RemoteDriveType.Ftp){
  3892. // 调用RemoteDriveManager的createFTPFolder方法
  3893. this.getUIContext().getPromptAction().showToast({ message: 'FTP目前不支持创建文件夹' });
  3894. }else{
  3895. this.getUIContext().getPromptAction().showToast({ message: '当前账户类型不支持创建文件夹' });
  3896. }
  3897. // 创建成功后刷新当前目录
  3898. await this.webdavManager.loadFilesInfoFromAccount(this.selectedAccount,
  3899. this.currentDirectoryPath || this.selectedAccount.filepath || '/');
  3900. this.getUIContext().getPromptAction().showToast({
  3901. message: `文件夹 "${folderName}" 创建成功`
  3902. });
  3903. Logger.info(TAG, `heanup 文件夹创建成功`);
  3904. } catch (error) {
  3905. const err = error as Error;
  3906. Logger.error(TAG, `heanup 创建文件夹失败: ${err.message}`);
  3907. // 显示具体的错误信息
  3908. this.getUIContext().getPromptAction().showToast({
  3909. message: `创建失败: ${err.message}`
  3910. });
  3911. } finally {
  3912. this.isLoading = false;
  3913. }
  3914. }
  3915. }