WebDavMainPage.ets 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727
  1. import { BreadcrumbItem, 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 { promptAction, SymbolGlyphModifier, router, window, 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 { display } from '@kit.ArkUI';
  11. import { FileInfo } from '../viewmodel/FileInfo';
  12. import { emitter } from '@kit.BasicServicesKit';
  13. import { EventConstants } from '../common/constants/EventConstants';
  14. import { LazyDataSource } from '../common/util/LazyDataSource';
  15. import { ArrayUtil, PreferencesUtil, StrUtil, ToastUtil } from '@pura/harmony-utils';
  16. import { DialogHelper } from '@pura/harmony-dialog';
  17. import { ButtonFancyModifier,
  18. MenuModifier,
  19. ShadowModifier, SymbolGlyphFancyModifier } from '../common/util/AttributeModifierUtil';
  20. import { getRemoteDriveAccountLabel, getRemoteDriveDisplayLabel, getRemoteDrivePlaylistPrefix } from '../common/util/RemoteDriveLabel';
  21. import { RemoteDriveType } from '../common/enums/RemoteDriveType';
  22. import { Utility } from '../common/util/Utility';
  23. import { SettingPage } from './SettingPage';
  24. import { getCloudDiskIcon } from '../dialog/RemoteDriveAccountDialog';
  25. import { CreateFolderDialog } from '../dialog/CreateFolderDialog';
  26. import { UploadMusicPage } from './UploadMusicPage';
  27. /**
  28. * 歌单播放事件数据
  29. */
  30. interface PlaylistEventData {
  31. playlistId: string;
  32. playlistName: string;
  33. songCount: number;
  34. startIndex: number;
  35. isJump: boolean;
  36. songFilePaths: string[];
  37. // 移除webDavAuthInfo,现在直接使用videoItems中的webdav_account_id
  38. }
  39. interface WebDavMetadataUpdatePayload {
  40. filePath: string;
  41. pixelMapPath?: string;
  42. name?: string;
  43. artist?: string;
  44. }
  45. const TAG = 'heanup WebDavMainPage';
  46. // WebDAV歌曲数据全局内存存储
  47. let globalWebdavVideoItems: VideoItem[] = [];
  48. let globalWebdavCurrentPlayIndex: number = 0;
  49. // 导出函数供LocalMusic访问
  50. export function getWebdavVideoItems(): VideoItem[] {
  51. return globalWebdavVideoItems;
  52. }
  53. export function getWebdavCurrentPlayIndex(): number {
  54. return globalWebdavCurrentPlayIndex;
  55. }
  56. export function clearWebdavVideoItems(): void {
  57. globalWebdavVideoItems = [];
  58. globalWebdavCurrentPlayIndex = 0;
  59. }
  60. // URL解码函数
  61. function decodeUrlEncodedString(encodedStr: string): string {
  62. try {
  63. return decodeURIComponent(encodedStr);
  64. } catch (error) {
  65. // 如果解码失败,返回原始字符串
  66. return encodedStr;
  67. }
  68. }
  69. @Preview
  70. @Entry
  71. @Component
  72. export struct WebDavMainPage {
  73. @State appName: string = ''
  74. @State isShowUploadFile: boolean = false
  75. @State isShowTitleBar: boolean = true //是否显示分类导航条
  76. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  77. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  78. @State isCustomizeBg: boolean = false //自定义背景界面
  79. @StorageProp('isLandscape') isLandscape: boolean = false;
  80. @State blurValue: number = 0 //背景模糊
  81. @State bgBrightness: number = 0 //背景亮度
  82. @State customizeBgPath: string | undefined = '';
  83. private listScroller: ListScroller = new ListScroller()
  84. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  85. searchController: SearchController = new SearchController()
  86. @StorageProp('animationState') animationState: AnimationStatus= AnimationStatus.Running
  87. @State isNoJumpToHome: boolean = false //网盘播放不跳转首页
  88. @State isSearchMode: boolean = false
  89. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  90. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  91. @State webdavManager: RemoteDriveManager = RemoteDriveManager.getInstance();
  92. @State accounts: WebDavAccount[] = [];
  93. @Prop @Watch('onSwitchAccount') selectedAccount: WebDavAccount;
  94. @State songs: VideoItem[] = [];
  95. @State dataSource:LazyDataSource<VideoItem> = new LazyDataSource(this.songs)
  96. @Link mType: number;
  97. @Link offsetX: number;
  98. @Link isShowDrawer: boolean;
  99. @State isLoading: boolean = false;
  100. @State webDavFiles: FileInfo[] = []; // 直接在页面中保存文件列表副本
  101. @StorageProp('themeColor') themeColor: string = CommonConstants.DEFAULT_THEME_COLOR;
  102. @StorageProp('isDarkMode') isDarkMode: boolean = false;
  103. @State breadcrumbs:BreadcrumbItem[] = []//面包屑导航
  104. @State visibleFoldersState: FileInfo[] = []; // 改为普通状态变量
  105. @State isShowFileName: boolean = false//是否显示文件名
  106. @State isLongNameRoLL: boolean = true//长歌名滚动
  107. @State sortType: number = 0 //默认排序方式
  108. @State listRefreshKey: number = 0 // 列表刷新标识
  109. @Consume isMultiSelect: boolean
  110. @State selectedSongs: VideoItem[] = []
  111. @State isAllSelected: boolean = false
  112. @State isDeletingSelection: boolean = false
  113. private readonly metadataUpdateEvent: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  114. async onSwitchAccount(){
  115. console.log('onecold 切换账户:', this.selectedAccount.name);
  116. this.songs = [];
  117. this.visibleFoldersState = [];
  118. this.updateListData(this.songs)
  119. this.exitMultiSelect();
  120. // 注意:不再需要清空全局上下文,因为LocalMusic已改用实例变量缓存
  121. // 当新账户加载时,新的认证信息会自动覆盖旧的
  122. Logger.info(TAG, 'heanup 切换账户,准备加载新账户文件');
  123. this.isLoading = true;
  124. await this.webdavManager.loadFilesInfoFromAccount(this.selectedAccount)
  125. .catch((error: Error) => {
  126. Logger.error(TAG, '加载文件失败: ' + error.message);
  127. this.isLoading = false;
  128. });
  129. this.breadcrumbs = this.webdavManager.getBreadcrumbs();
  130. }
  131. updateListData(mList:Array<VideoItem>, noSort?: boolean){
  132. if (!noSort) {
  133. this.sortType = PreferencesUtil.getNumberSync('webDavSortType', 0)
  134. this.doSortType(this.sortType)
  135. }
  136. this.dataSource.pushArrayData(mList)
  137. if(mList.length > 0){
  138. setTimeout(() => {
  139. this.listScroller.scrollToIndex(0)
  140. },200)
  141. }
  142. }
  143. // 更新可见文件夹列表
  144. private updateVisibleFolders(): void {
  145. try {
  146. // 安全检查webDavFiles
  147. if (!this.webDavFiles || !Array.isArray(this.webDavFiles)) {
  148. this.visibleFoldersState = [];
  149. return;
  150. }
  151. const allFolders = this.webDavFiles.filter(f => f.isDirectory);
  152. const isNavAccount = this.selectedAccount?.webType === RemoteDriveType.Navidrome;
  153. if (isNavAccount) {
  154. const sortedNavFolders = allFolders.sort((a, b) => a.fileName.localeCompare(b.fileName));
  155. this.visibleFoldersState = sortedNavFolders;
  156. return;
  157. }
  158. const visible: FileInfo[] = [];
  159. for (let i = 0; i < allFolders.length; i++) {
  160. const folder = allFolders[i];
  161. // 安全检查folder对象
  162. if (!folder || typeof folder.fileName !== 'string') {
  163. continue;
  164. }
  165. let shouldShow = this.isDirectChildOfCurrentPath(folder);
  166. if (shouldShow) {
  167. visible.push(folder);
  168. }
  169. }
  170. console.log('更新文件夹列表:', visible);
  171. this.visibleFoldersState = visible;
  172. } catch (error) {
  173. Logger.error(TAG, '更新文件夹列表失败:', error.toString());
  174. this.visibleFoldersState = [];
  175. }
  176. this.isShowTitleBar = true
  177. }
  178. private isSongSelected(song: VideoItem): boolean {
  179. return this.selectedSongs.some(item => item.filePath === song.filePath);
  180. }
  181. private enterMultiSelect(song: VideoItem): void {
  182. if (!this.isMultiSelect) {
  183. this.isMultiSelect = true;
  184. this.selectedSongs = [song];
  185. this.isAllSelected = this.selectedSongs.length === this.songs.length && this.songs.length > 0;
  186. return;
  187. }
  188. if (!this.isSongSelected(song)) {
  189. this.toggleSongSelection(song);
  190. }
  191. }
  192. private toggleSongSelection(song: VideoItem): void {
  193. if (!this.isMultiSelect) {
  194. this.isMultiSelect = true;
  195. }
  196. const exists = this.isSongSelected(song);
  197. if (exists) {
  198. const next = this.selectedSongs.filter(item => item.filePath !== song.filePath);
  199. this.selectedSongs = next;
  200. this.isAllSelected = next.length > 0 && next.length === this.songs.length;
  201. if (next.length === 0) {
  202. this.exitMultiSelect();
  203. }
  204. } else {
  205. const next = [...this.selectedSongs, song];
  206. this.selectedSongs = next;
  207. this.isAllSelected = next.length === this.songs.length && this.songs.length > 0;
  208. }
  209. }
  210. private handleCheckboxSelection(song: VideoItem, checked: boolean): void {
  211. if (!this.isMultiSelect) {
  212. this.isMultiSelect = true;
  213. }
  214. const exists = this.isSongSelected(song);
  215. if (checked && !exists) {
  216. this.toggleSongSelection(song);
  217. } else if (!checked && exists) {
  218. this.toggleSongSelection(song);
  219. }
  220. }
  221. private toggleSelectAll(): void {
  222. if (this.isAllSelected) {
  223. this.selectedSongs = [];
  224. this.isAllSelected = false;
  225. return;
  226. }
  227. if (!this.isMultiSelect) {
  228. this.isMultiSelect = true;
  229. }
  230. this.selectedSongs = this.songs.slice();
  231. this.isAllSelected = this.selectedSongs.length > 0 && this.selectedSongs.length === this.songs.length;
  232. }
  233. private exitMultiSelect(): void {
  234. this.isMultiSelect = false;
  235. this.selectedSongs = [];
  236. this.isAllSelected = false;
  237. console.info('onecold this.isMultiSelect '+this.isMultiSelect)
  238. }
  239. private syncSelectionAfterRefresh(): void {
  240. if (!this.isMultiSelect) {
  241. return;
  242. }
  243. const currentKeys: Set<string> = new Set(this.songs.map(item => item.filePath));
  244. const filtered = this.selectedSongs.filter(item => currentKeys.has(item.filePath));
  245. if (filtered.length !== this.selectedSongs.length) {
  246. this.selectedSongs = filtered;
  247. }
  248. this.isAllSelected = filtered.length > 0 && filtered.length === this.songs.length;
  249. if (filtered.length === 0) {
  250. this.exitMultiSelect();
  251. }
  252. }
  253. private confirmDeleteSelected(): void {
  254. if (!this.selectedAccount) {
  255. this.getUIContext().getPromptAction().showToast({ message: `请先选择${getRemoteDriveAccountLabel()}` });
  256. return;
  257. }
  258. if (!this.isMultiSelect || this.selectedSongs.length === 0) {
  259. this.getUIContext().getPromptAction().showToast({ message: '请先选择要删除的文件' });
  260. return;
  261. }
  262. this.getUIContext().showAlertDialog({
  263. title: '删除文件',
  264. message: `确定删除选中的${this.selectedSongs.length}个文件吗?`,
  265. primaryButton: {
  266. value: '取消',
  267. action: () => {}
  268. },
  269. secondaryButton: {
  270. value: '删除',
  271. fontColor: Color.Red,
  272. action: () => {
  273. void this.performDeleteSelected();
  274. }
  275. }
  276. });
  277. }
  278. private async performDeleteSelected(): Promise<void> {
  279. if (!this.selectedAccount || this.selectedSongs.length === 0) {
  280. return;
  281. }
  282. this.isDeletingSelection = true;
  283. try {
  284. await this.webdavManager.deleteRemoteSongs(this.selectedAccount, this.selectedSongs.slice());
  285. await this.webdavManager.loadFilesInfoFromAccount(this.selectedAccount, this.webdavManager.currentPath);
  286. this.exitMultiSelect();
  287. this.getUIContext().getPromptAction().showToast({ message: '删除成功' });
  288. this.exitMultiSelect()
  289. } catch (error) {
  290. const err = error as Error;
  291. this.getUIContext().getPromptAction().showToast({ message: `删除失败: ${err.message}` });
  292. } finally {
  293. this.isDeletingSelection = false;
  294. }
  295. }
  296. private buildSongMetaLine(song: VideoItem): string {
  297. const parts: string[] = [];
  298. if (StrUtil.isNotEmpty(song.duration)) {
  299. parts.push(song.duration as string);
  300. } else if (StrUtil.isNotEmpty(song.size)) {
  301. parts.push(decodeUrlEncodedString(song.size as string));
  302. }
  303. if (parts.length === 0 && StrUtil.isNotEmpty(song.cTime)) {
  304. parts.push(song.cTime as string);
  305. }
  306. return parts.join(' · ');
  307. }
  308. // 对话框控制器
  309. private accountDialogController: CustomDialogController | null = null;
  310. // 保存事件处理器引用,用于取消订阅
  311. private eventHandler: (event: string) => void = (event: string) => {
  312. this.handleWebdavEvent(event);
  313. };
  314. initSetting(){
  315. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  316. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  317. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  318. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  319. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  320. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  321. this.sortType = PreferencesUtil.getNumberSync('webDavSortType', 0)
  322. this.isNoJumpToHome = PreferencesUtil.getBooleanSync('isNoJumpToHome', true)
  323. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  324. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  325. }
  326. aboutToAppear(): void {
  327. Utility.getAppName(getContext(this)).then((appName: string) => {
  328. this.appName = appName
  329. })
  330. this.initSetting()
  331. let eventSetting: emitter.InnerEvent = { eventId: 333 }
  332. // 监听广播事件(通用设置配置更新)
  333. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  334. this.initSetting()
  335. });
  336. // 加载账户列表
  337. this.loadAccounts();
  338. this.loadFiles()
  339. this.breadcrumbs = this.webdavManager.getBreadcrumbs();
  340. // 订阅WebDAV状态变化
  341. this.webdavManager.subscribe(this.eventHandler);
  342. this.subscribeWebDavMetadataUpdates();
  343. }
  344. aboutToDisappear(): void {
  345. // 取消订阅
  346. this.webdavManager.unsubscribe(this.eventHandler);
  347. emitter.off(EventConstants.EVENT_WEBDAV_METADATA_UPDATED);
  348. }
  349. // 处理WebDAV事件
  350. private handleWebdavEvent(event: string): void {
  351. switch (event) {
  352. case RemoteDriveManagerStates.LoadFilesInfoSucceed:
  353. this.songs = this.webdavManager.webDavSongs;
  354. this.updateListData(this.songs)
  355. // 直接引用webdavManager的数组,避免@Observed序列化问题
  356. this.webDavFiles = this.webdavManager.webDavFiles;
  357. this.isLoading = false;
  358. // 更新可见文件夹列表
  359. this.updateVisibleFolders();
  360. this.breadcrumbs = this.webdavManager.getBreadcrumbs();
  361. this.syncSelectionAfterRefresh();
  362. // promptAction.showToast({
  363. // message: '加载成功: ' + this.webDavFiles.filter(f => f.isDirectory).length + '个文件夹, ' + this.songs.length + '首歌曲'
  364. // });
  365. break;
  366. case RemoteDriveManagerStates.LoadFilesInfoFailed:
  367. this.isLoading = false;
  368. // this.getUIContext().getPromptAction().showToast({ message: '加载失败' });
  369. break;
  370. case RemoteDriveManagerStates.InsertAccountSucceed:
  371. case RemoteDriveManagerStates.EditAccountSucceed:
  372. case RemoteDriveManagerStates.RemoveAccountSucceed:
  373. this.loadAccounts();
  374. break;
  375. }
  376. }
  377. private subscribeWebDavMetadataUpdates(): void {
  378. emitter.on(this.metadataUpdateEvent, (eventData: emitter.EventData) => {
  379. const payloads = eventData?.data as WebDavMetadataUpdatePayload[] | undefined;
  380. if (!payloads || payloads.length === 0) {
  381. Logger.info(TAG, 'WebDav metadata event received but payload empty');
  382. return;
  383. }
  384. Logger.info(TAG, `WebDav metadata event payload count: ${payloads.length}`);
  385. this.handleWebDavMetadataUpdates(payloads);
  386. });
  387. }
  388. private handleWebDavMetadataUpdates(payloads: WebDavMetadataUpdatePayload[]): void {
  389. if (!payloads || payloads.length === 0) {
  390. return;
  391. }
  392. Logger.info(TAG, 'handleWebDavMetadataUpdates start');
  393. let hasChanges = false;
  394. for (let i = 0; i < payloads.length; i++) {
  395. const payload = payloads[i];
  396. if (!payload || !payload.filePath) {
  397. continue;
  398. }
  399. Logger.info(TAG, `WebDav metadata detail path=${payload.pixelMapPath ?? 'null'}`);
  400. const songUpdated = this.updateSongMetadata(payload);
  401. if (songUpdated) {
  402. hasChanges = true;
  403. Logger.info(TAG, `metadata updated for ${payload.filePath}`);
  404. }
  405. }
  406. if (!hasChanges) {
  407. Logger.info(TAG, 'handleWebDavMetadataUpdates no changes detected');
  408. return;
  409. }
  410. const clonedSongs: VideoItem[] = [];
  411. for (let i = 0; i < this.songs.length; i++) {
  412. clonedSongs.push(this.cloneSong(this.songs[i]));
  413. }
  414. this.songs = clonedSongs;
  415. this.dataSource.pushArrayData(clonedSongs);
  416. this.listRefreshKey++;
  417. Logger.info(TAG, 'handleWebDavMetadataUpdates trigger refresh');
  418. }
  419. private updateSongMetadata(payload: WebDavMetadataUpdatePayload): boolean {
  420. if (!payload.filePath) {
  421. return false;
  422. }
  423. const targetIndex = this.findSongIndex(payload.filePath);
  424. if (targetIndex < 0) {
  425. return false;
  426. }
  427. const targetSong = this.songs[targetIndex];
  428. let mutated = false;
  429. if (payload.pixelMapPath && payload.pixelMapPath.length > 0) {
  430. targetSong.pixelMapPath = payload.pixelMapPath;
  431. mutated = true;
  432. }
  433. if (payload.name && payload.name.length > 0) {
  434. targetSong.name = payload.name;
  435. mutated = true;
  436. }
  437. if (payload.artist && payload.artist.length > 0) {
  438. targetSong.artist = payload.artist;
  439. mutated = true;
  440. }
  441. return mutated;
  442. }
  443. private findSongIndex(filePath: string): number {
  444. for (let i = 0; i < this.songs.length; i++) {
  445. if (this.songs[i].filePath === filePath) {
  446. return i;
  447. }
  448. }
  449. return -1;
  450. }
  451. private cloneSong(item: VideoItem): VideoItem {
  452. const clone = new VideoItem(
  453. item.name,
  454. item.id,
  455. item.filePath,
  456. item.type,
  457. item.videoSize,
  458. item.cTime,
  459. item.size,
  460. item.pixelMapPath,
  461. item.artist,
  462. item.album,
  463. item.fileName,
  464. item.lastPlayed
  465. );
  466. clone.duration = item.duration;
  467. clone.mimeType = item.mimeType;
  468. clone.trackCount = item.trackCount;
  469. clone.sampleRate = item.sampleRate;
  470. clone.size = item.size;
  471. clone.webdav_account_id = item.webdav_account_id;
  472. clone.remote_rel_path = item.remote_rel_path;
  473. clone.artist = item.artist;
  474. clone.album = item.album;
  475. clone.lyricContent = item.lyricContent;
  476. clone.pixelMapPath = item.pixelMapPath;
  477. clone.cTime = item.cTime;
  478. clone.fileName = item.fileName;
  479. clone.md5Str = item.md5Str;
  480. clone.bit_rate = item.bit_rate;
  481. clone.probe_score = item.probe_score;
  482. clone.year = item.year;
  483. clone.nb_streams = item.nb_streams;
  484. clone.nb_programs = item.nb_programs;
  485. clone.genre = item.genre;
  486. clone.track = item.track;
  487. clone.disc = item.disc;
  488. clone.channels = item.channels;
  489. clone.channel_layout = item.channel_layout;
  490. clone.start_time = item.start_time;
  491. clone.ALBUMARTIST = item.ALBUMARTIST;
  492. clone.COMPOSER = item.COMPOSER;
  493. clone.COMMENT = item.COMMENT;
  494. clone.LYRICIST = item.LYRICIST;
  495. clone.pyStr = item.pyStr;
  496. clone.extra_json = item.extra_json;
  497. clone.parentPath = item.parentPath;
  498. clone.isFav = item.isFav;
  499. clone.playCount = item.playCount;
  500. clone.lastPlayed = item.lastPlayed;
  501. clone.videoSize = item.videoSize;
  502. clone.isFav = item.isFav;
  503. return clone;
  504. }
  505. // 加载账户列表
  506. private loadAccounts(): void {
  507. this.accounts = this.webdavManager.getAllWebDavAccounts();
  508. }
  509. // 加载文件列表
  510. private loadFiles(): void {
  511. if (!this.selectedAccount) {
  512. this.getUIContext().getPromptAction().showToast({ message: '请先选择账户' });
  513. return;
  514. }
  515. this.isLoading = true;
  516. this.webdavManager.loadFilesInfoFromWebdav()
  517. .catch((error: Error) => {
  518. Logger.error(TAG, '加载文件失败: ' + error.message);
  519. this.isLoading = false;
  520. });
  521. }
  522. // 进入文件夹
  523. private enterFolder(folder: FileInfo): void {
  524. this.isLoading = true;
  525. this.webdavManager.enterFolder(folder)
  526. .catch((error: Error) => {
  527. Logger.error(TAG, '进入文件夹失败: ' + error.message);
  528. this.isLoading = false;
  529. });
  530. }
  531. // 检查是否为当前目录的直接子项
  532. private isDirectChildOfCurrentPath(folder: FileInfo): boolean {
  533. const currentPath = this.webdavManager.currentPath || '';
  534. // 如果在根目录(currentPath为空或'/'),显示所有第一级文件夹
  535. if (currentPath === '' || currentPath === '/') {
  536. const folderPath = folder.href.replace(/\/$/, ''); // 去掉尾部斜杠
  537. return folder.href.startsWith('/') &&
  538. folder.href !== '/' &&
  539. !folderPath.substring(1).includes('/');
  540. }
  541. // 非根目录情况,计算相对路径
  542. let relativePath = folder.href;
  543. if (currentPath !== '/') {
  544. relativePath = folder.href.replace(currentPath, '');
  545. }
  546. relativePath = relativePath.replace(/^\//, '').replace(/\/$/, '');
  547. // 只有相对路径不为空且不包含/时才认为是直接子项
  548. return relativePath !== '' && !relativePath.includes('/');
  549. }
  550. // 返回上级目录
  551. private goBack(): void {
  552. if(this.webdavManager.canGoBack()){
  553. this.isLoading = true;
  554. this.webdavManager.goBack()
  555. .catch((error: Error) => {
  556. Logger.error(TAG, '返回失败: ' + error.message);
  557. this.isLoading = false;
  558. });
  559. this.breadcrumbs = this.webdavManager.getBreadcrumbs();
  560. }
  561. }
  562. // 切换账户
  563. private switchAccount(account: WebDavAccount): void {
  564. this.selectedAccount = account;
  565. this.songs = [];
  566. this.updateListData(this.songs)
  567. }
  568. // 播放WebDAV歌曲
  569. private playSong(song: VideoItem, index: number,isJump:boolean=false): void {
  570. try {
  571. Logger.info(TAG, `heanup === WebDAV playSong 方法被调用 ===`);
  572. Logger.info(TAG, 'heanup 播放指定歌曲: ' + song.name + ', 索引: ' + index);
  573. Logger.info(TAG, 'heanup 歌曲列表长度: ' + this.songs.length);
  574. // 检查歌曲是否有webdav_account_id
  575. Logger.info(TAG, `heanup 播放歌曲的webdav_account_id: ${song.webdav_account_id || '未设置'}`);
  576. // 确保所有歌曲都设置了正确的webdav_account_id
  577. if (this.selectedAccount && this.selectedAccount.id) {
  578. const accountIds = this.songs.map(s => s.webdav_account_id).filter(id => id);
  579. Logger.info(TAG, `heanup 当前歌曲列表中有 ${accountIds.length}/${this.songs.length} 首歌曲设置了webdav_account_id`);
  580. // 如果发现歌曲缺少webdav_account_id,立即设置
  581. this.songs.forEach((item, idx) => {
  582. if (!item.webdav_account_id) {
  583. item.webdav_account_id = this.selectedAccount!.id.toString();
  584. Logger.info(TAG, `heanup 为歌曲 "${item.name}" 设置webdav_account_id: ${item.webdav_account_id}`);
  585. }
  586. });
  587. }
  588. // 直接使用当前的VideoItem数组
  589. const videoItems: VideoItem[] = this.songs;
  590. const songFilePaths: string[] = [];
  591. for (let i = 0; i < this.songs.length; i++) {
  592. const item = this.songs[i];
  593. songFilePaths.push(item.filePath); // 使用filePath作为文件路径
  594. }
  595. // 直接通过事件传递videoItems数据,不使用GlobalContext
  596. const eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY };
  597. const playlistData: PlaylistEventData = {
  598. playlistId: 'webdav-playlist', // 使用特殊的ID标识网盘播放列表
  599. playlistName: `${getRemoteDriveDisplayLabel(this.selectedAccount?.webType)} - ${this.selectedAccount?.name || '未知账户'}`,
  600. songCount: this.songs.length,
  601. startIndex: index,
  602. isJump: isJump,//设置true会弹出播放页
  603. songFilePaths: songFilePaths
  604. };
  605. // 保存videoItems到全局内存
  606. globalWebdavVideoItems = videoItems;
  607. globalWebdavCurrentPlayIndex = index;
  608. Logger.info(TAG, `heanup 保存WebDAV歌曲到全局内存,长度: ${videoItems.length}, 索引: ${index}`);
  609. // 发送播放请求事件,只传递索引信息
  610. emitter.emit(eventPlaylistPlay, { data: playlistData });
  611. Logger.info(TAG, `heanup 发送WebDAV播放事件,只传递索引: ${index}`);
  612. if(!this.isNoJumpToHome){
  613. // 跳转到首页播放器
  614. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  615. this.mType = 0
  616. })
  617. }
  618. } catch (error) {
  619. const err = error as Error;
  620. Logger.error(TAG, '播放歌曲失败: ' + err.message);
  621. this.getUIContext().getPromptAction().showToast({ message: '播放失败' });
  622. }
  623. }
  624. /**
  625. * 一键创建歌单:将当前WebDAV歌曲全部加入新歌单
  626. */
  627. private async createPlaylistFromCurrentWebDav(): Promise<void> {
  628. try {
  629. Logger.info(TAG, 'heanup 一键创建歌单开始');
  630. if (!this.selectedAccount || !this.selectedAccount.id) {
  631. this.getUIContext().getPromptAction().showToast({ message: `请先选择${getRemoteDriveAccountLabel()}` });
  632. return;
  633. }
  634. if (!this.songs || this.songs.length === 0) {
  635. // 回退到manager内的歌曲(可能还未复制到页面state)
  636. this.songs = this.webdavManager.webDavSongs;
  637. Logger.info(TAG, `heanup 页面songs为空,回退webdavManager.webDavSongs,长度=${this.songs.length}`);
  638. if (this.songs.length === 0) {
  639. this.getUIContext().getPromptAction().showToast({ message: '当前目录没有可添加的歌曲' });
  640. return;
  641. }
  642. }
  643. Logger.info(TAG, `heanup 歌单创建前歌曲数量: ${this.songs.length}`);
  644. // 确保每首歌都有webdav_account_id
  645. for (let i = 0; i < this.songs.length; i++) {
  646. if (!this.songs[i].webdav_account_id) {
  647. this.songs[i].webdav_account_id = this.selectedAccount.id.toString();
  648. }
  649. }
  650. // 构建歌单名称:账户名 + 当前路径(简化)
  651. const rawPath = this.webdavManager.currentPath || '/';
  652. const shortPath = rawPath === '/' ? '根目录' : rawPath.replace(/\/$/, '').split('/').slice(-1)[0];
  653. const playlistName = `${getRemoteDrivePlaylistPrefix(this.selectedAccount.webType)}-${this.selectedAccount.name}-${shortPath}`;
  654. // 创建歌单
  655. // 安全获取HostContext
  656. const uiContext = this.getUIContext();
  657. const hostCtx = uiContext ? uiContext.getHostContext() : undefined;
  658. if (!hostCtx) {
  659. this.getUIContext().getPromptAction().showToast({ message: '无法获取上下文' });
  660. return;
  661. }
  662. const playlistModule = await import('../common/util/PlaylistTable');
  663. const mediaModule = await import('../common/util/MediaTable');
  664. const playlistTable = new playlistModule.default(hostCtx);
  665. const mediaTable = new mediaModule.default(hostCtx);
  666. // 等待MediaTable底层RDB初始化完成
  667. await new Promise<void>((resolve) => {
  668. mediaTable.getRdbStore(hostCtx, () => {
  669. Logger.info(TAG, 'heanup mediaTable RDB 初始化完成');
  670. resolve();
  671. });
  672. });
  673. // 先将WebDAV歌曲入库(若不存在)
  674. let upsertSuccess = 0;
  675. for (let i = 0; i < this.songs.length; i++) {
  676. const v = this.songs[i];
  677. if (!v.id || v.id === '') {
  678. // 使用filePath作为唯一ID
  679. v.id = v.filePath;
  680. }
  681. if (!v.parentPath) {
  682. const idxp = v.filePath.lastIndexOf('/');
  683. if (idxp > 0) {
  684. v.parentPath = v.filePath.substring(0, idxp);
  685. }
  686. }
  687. const ok = await mediaTable.upsertWebDavVideoItem(v);
  688. Logger.info(TAG, `heanup upsert 第${i+1}/${this.songs.length}首: ${v.filePath} => ${ok}`);
  689. if (ok) {
  690. upsertSuccess++;
  691. }
  692. }
  693. Logger.info(TAG, `heanup WebDAV歌曲入库完成: 成功 ${upsertSuccess}/${this.songs.length}`);
  694. // 先查询是否已有同名歌单,避免重复创建导致混淆
  695. const existing = (await playlistTable.queryAllPlaylists()).find(p => p.name === playlistName);
  696. if (existing) {
  697. this.getUIContext().getPromptAction().showToast({ message: '歌单已存在,直接追加歌曲' });
  698. const filePathsExist: string[] = this.songs.map(s => s.filePath);
  699. await playlistTable.addSongsToPlaylist(existing.id, filePathsExist);
  700. router.pushUrl({ url: 'pages/PlaylistDetailPage', params: { playlist: existing } });
  701. return;
  702. }
  703. Logger.info(TAG, `heanup 准备创建歌单: ${playlistName}`);
  704. const created = await playlistTable.createPlaylist(playlistName, `来自${getRemoteDriveDisplayLabel(this.selectedAccount.webType)}: ${this.selectedAccount.name} 路径: ${rawPath}`);
  705. if (!created) {
  706. this.getUIContext().getPromptAction().showToast({ message: '歌单创建失败' });
  707. return;
  708. }
  709. // 查询刚创建的歌单ID
  710. const playlists = await playlistTable.queryAllPlaylists();
  711. const target = playlists.reverse().find(p => p.name === playlistName); // 取最近创建的同名歌单
  712. if (!target) {
  713. this.getUIContext().getPromptAction().showToast({ message: '无法找到新建歌单' });
  714. return;
  715. }
  716. // 批量添加歌曲
  717. const filePaths: string[] = this.songs.map(s => s.filePath);
  718. Logger.info(TAG, `heanup 开始批量添加歌曲到歌单: ${target.id}`);
  719. const addResult = await playlistTable.addSongsToPlaylist(target.id, filePaths);
  720. Logger.info(TAG, `heanup 批量添加结果: ${addResult}`);
  721. if (!addResult) {
  722. Logger.warn(TAG, '批量添加歌曲返回false,可能全部已存在或写入失败');
  723. }
  724. this.getUIContext().getPromptAction().showToast({ message: `歌单创建成功: ${playlistName}` });
  725. Logger.info(TAG, `heanup 一键创建歌单成功: ${playlistName}, 添加 ${filePaths.length} 首歌曲`);
  726. // 跳转到歌单详情页面
  727. router.pushUrl({ url: 'pages/PlaylistDetailPage', params: { playlist: target } });
  728. } catch (error) {
  729. Logger.error(TAG, '一键创建歌单失败: ' + (error as Error).message);
  730. this.getUIContext().getPromptAction().showToast({ message: '一键创建歌单失败' });
  731. }
  732. }
  733. // 导航到指定层级的面包屑路径
  734. private async navigateToBreadcrumb(crumb: BreadcrumbItem): Promise<void> {
  735. if (!crumb) {
  736. return;
  737. }
  738. try {
  739. this.isLoading = true;
  740. await this.webdavManager.enterFolderFromPath(crumb.path);
  741. } catch (error) {
  742. Logger.error(TAG, '导航到面包屑路径失败: ' + (error as Error).message);
  743. this.isLoading = false;
  744. }
  745. }
  746. @Builder
  747. MoreMenuBuilder() {
  748. Menu() {
  749. MenuItem({
  750. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  751. content: $r('app.string.onekey_add_playlist')
  752. })
  753. .onClick(async () => {
  754. this.createPlaylistFromCurrentWebDav();
  755. })
  756. MenuItem({
  757. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_up_to_line')),
  758. content: $r('app.string.upload_music_file')
  759. })
  760. .onClick(async () => {
  761. // this.navigateToUploadPage();
  762. this.isShowUploadFile = !this.isShowUploadFile
  763. })
  764. MenuItem({
  765. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  766. content: $r('app.string.create_foder')
  767. })
  768. .onClick(async () => {
  769. this.showCreateFolderDialog();
  770. })
  771. }.attributeModifier(new MenuModifier())
  772. }
  773. @Builder
  774. SortMenuBuilder() {
  775. Menu() {
  776. MenuItem({
  777. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  778. content: $r('app.string.sort_by_name')
  779. })
  780. .onClick(async () => {
  781. this.doSortType(0)
  782. PreferencesUtil.put("webDavSortType", 0)
  783. })
  784. MenuItem({
  785. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  786. content: '按名称降序'
  787. })
  788. .onClick(async () => {
  789. this.doSortType(1)
  790. PreferencesUtil.put("webDavSortType", 1)
  791. })
  792. MenuItem({
  793. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  794. content:'按时间升序'
  795. })
  796. .onClick(async () => {
  797. this.doSortType(2)
  798. PreferencesUtil.put("webDavSortType", 2)
  799. })
  800. MenuItem({
  801. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  802. content: '按时间降序'
  803. })
  804. .onClick(async () => {
  805. this.doSortType(3)
  806. PreferencesUtil.put("webDavSortType", 3)
  807. })
  808. MenuItem({
  809. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  810. content:'按大小升序'
  811. })
  812. .onClick(async () => {
  813. this.doSortType(4)
  814. PreferencesUtil.put("webDavSortType", 4)
  815. })
  816. MenuItem({
  817. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  818. content: '按大小降序'
  819. })
  820. .onClick(async () => {
  821. this.doSortType(5)
  822. PreferencesUtil.put("webDavSortType", 5)
  823. })
  824. }.attributeModifier(new MenuModifier())
  825. }
  826. doSortType(index: number) {
  827. // 对歌曲列表进行排序
  828. switch (index) {
  829. case 0:
  830. Utility.doSortListAscending(this.songs,this.isShowFileName)
  831. this.visibleFoldersState.sort((a, b) => {
  832. return a.fileName.localeCompare(b.fileName);
  833. });
  834. break;
  835. case 1:
  836. Utility.doSortListDescending(this.songs,this.isShowFileName)
  837. this.visibleFoldersState.sort((a, b) => {
  838. return b.fileName.localeCompare(a.fileName);
  839. });
  840. break;
  841. case 2:
  842. this.songs.sort((a, b) => {
  843. return a.cTime.localeCompare(b.cTime);
  844. });
  845. this.visibleFoldersState.sort((a, b) => {
  846. return a.time-b.time;
  847. });
  848. break;
  849. case 3:
  850. this.songs.sort((a, b) => {
  851. return b.cTime.localeCompare(a.cTime);
  852. });
  853. this.visibleFoldersState.sort((a, b) => {
  854. return b.time-a.time;
  855. });
  856. break;
  857. case 4:
  858. this.songs.sort((a, b) => {
  859. return a.videoSize - b.videoSize;
  860. });
  861. break;
  862. case 5:
  863. this.songs.sort((a, b) => {
  864. return b.videoSize - a.videoSize;
  865. });
  866. break;
  867. }
  868. this.updateListData(this.songs,true)
  869. }
  870. @Builder
  871. topTitleBar(){
  872. Column() {
  873. Row({ space: 15 }) {
  874. if (!this.isSearchMode ) {
  875. //左侧滑动按钮
  876. Button({ type: ButtonType.Circle, stateEffect: true }) {
  877. SymbolGlyph($r('sys.symbol.sort'))
  878. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  879. }
  880. .attributeModifier(new ButtonFancyModifier(40, 40))
  881. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  882. .animation({ duration: 300, curve: Curve.Ease })
  883. .onClick(() => {
  884. this.getUIContext().animateTo({ duration: 555 }, () => {
  885. // 动画闭包内控制Image组件的出现和消失
  886. this.isShowDrawer = !this.isShowDrawer
  887. this.offsetX = 0
  888. })
  889. })
  890. .attributeModifier(new ShadowModifier())
  891. .zIndex(0)
  892. Text(this.selectedAccount.name)
  893. .margin({left:3,right:10})
  894. .fontColor($r('app.color.text_color'))
  895. .fontSize(19)
  896. .maxLines(1)
  897. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  898. .layoutWeight(1)
  899. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  900. }else{
  901. //左侧搜索返回按钮
  902. Button({ type: ButtonType.Circle, stateEffect: true }) {
  903. SymbolGlyph($r('sys.symbol.chevron_left'))
  904. .attributeModifier(new SymbolGlyphFancyModifier(24, '', ''))
  905. }
  906. .attributeModifier(new ButtonFancyModifier(40, 40))
  907. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  908. .animation({ duration: 300, curve: Curve.Ease })
  909. .onClick(() => {
  910. this.isSearchMode = false
  911. this.onSearchInput('')
  912. })
  913. .attributeModifier(new ShadowModifier())
  914. .zIndex(0)
  915. }
  916. //搜索框
  917. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  918. .searchButton('搜索',{fontColor:this.themeColor})
  919. .searchIcon({
  920. src: $r('sys.media.ohos_ic_public_search_filled')
  921. })
  922. .cancelButton({
  923. style: CancelButtonStyle.CONSTANT,
  924. icon: {
  925. src: $r('sys.media.ohos_ic_public_cancel_filled')
  926. }
  927. })
  928. .layoutWeight(1)
  929. .height(35)
  930. .maxLength(20)
  931. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  932. .placeholderColor(Color.Grey)
  933. .placeholderFont({ size: 14, weight: 400 })
  934. .textFont({ size: 14, weight: 400 })
  935. .onSubmit((value: string) => {
  936. console.log('onecold onSubmit ='+value)
  937. this.searchController.stopEditing()
  938. this.onSearchInput(this.searchText);
  939. })
  940. .onChange((value: string) => {
  941. console.log('onecold onChange ='+value)
  942. this.onSearchInput(value);
  943. })
  944. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  945. .animation({ duration: 300, curve: Curve.Ease })
  946. //搜索按钮
  947. if (!this.isSearchMode) {
  948. Button({ type: ButtonType.Circle, stateEffect: true }) {
  949. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  950. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  951. }
  952. .attributeModifier(new ButtonFancyModifier(40, 40))
  953. .animation({ duration: 300, curve: Curve.Ease })
  954. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  955. .attributeModifier(new ShadowModifier())
  956. .zIndex(0)
  957. .onClick(()=>{
  958. this.filteredFolderList = [...this.visibleFoldersState]; // 显示所有文件夹
  959. this.isSearchMode = true
  960. })
  961. //排序按钮
  962. Button({ type: ButtonType.Circle, stateEffect: true }) {
  963. SymbolGlyph($r('sys.symbol.list_number'))
  964. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  965. }
  966. .attributeModifier(new ButtonFancyModifier(40, 40))
  967. .animation({ duration: 300, curve: Curve.Ease })
  968. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  969. .bindMenu(this.SortMenuBuilder)
  970. .attributeModifier(new ShadowModifier())
  971. .zIndex(0)
  972. //添加/上传综合按钮
  973. Button({ type: ButtonType.Circle, stateEffect: true }) {
  974. SymbolGlyph($r('sys.symbol.plus'))
  975. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  976. }
  977. .attributeModifier(new ButtonFancyModifier(40, 40))
  978. .animation({ duration: 300, curve: Curve.Ease })
  979. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  980. .bindMenu(this.MoreMenuBuilder)
  981. .attributeModifier(new ShadowModifier())
  982. .zIndex(0)
  983. .bindContentCover($$this.isShowUploadFile, this.UploadFielBuilder(), {
  984. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  985. })
  986. }
  987. }
  988. }
  989. .padding({ top: this.topSafeHeight + 10, left: 10, right: 10, bottom: 2 })
  990. .width('100%')
  991. }
  992. @Builder
  993. UploadFielBuilder() {
  994. Scroll() {
  995. Column() {
  996. UploadMusicPage({
  997. accountId: this.selectedAccount.id,
  998. isShowUploadFile:this.isShowUploadFile,
  999. onResult:(result:boolean)=>{
  1000. console.info("heanup onResult,上传成功,刷新列表")
  1001. if(result){
  1002. // 上传文件成功后刷新当前路径的列表
  1003. if(this.selectedAccount.webType==RemoteDriveType.Baidu){
  1004. ToastUtil.showToast(`由于百度网盘限制,百度网盘的上传路径是apps/${this.appName}`)
  1005. }
  1006. this.refreshFileListAfterUpload()
  1007. }
  1008. },
  1009. })
  1010. }
  1011. }
  1012. .width('100%')
  1013. .height('100%')
  1014. }
  1015. //搜索功能的实现
  1016. @State searchText: string = ''; // 用户输入内容
  1017. @State filteredList: Array<VideoItem> = []; // 过滤后的歌曲结果
  1018. @State filteredFolderList: Array<FileInfo> = []; // 过滤后的文件夹结果
  1019. // 实时搜索逻辑(带防抖)
  1020. // 实时搜索逻辑(带防抖)
  1021. private onSearchInput(value: string) {
  1022. this.searchText = value.trim();
  1023. let mSearchList: Array<VideoItem> = []
  1024. mSearchList = this.songs
  1025. // 新增条件判断:空输入时显示所有数据
  1026. if (this.searchText === '') {
  1027. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  1028. this.filteredFolderList = [...this.visibleFoldersState]; // 显示所有文件夹
  1029. } else {
  1030. this.filteredList = mSearchList.filter((item: VideoItem) => {
  1031. //支持模糊匹配和艺术家 专辑匹配
  1032. const regex = new RegExp(this.searchText.toLowerCase().replace(/\s+/g, '.*'), 'i');
  1033. return regex.test(item.name.toLowerCase())||
  1034. regex.test(item.fileName?.toLowerCase() ?? "") ||
  1035. regex.test(item.artist?.toLowerCase() ?? "") ||
  1036. regex.test(item.album?.toLowerCase() ?? "")
  1037. });
  1038. // 对文件夹进行过滤
  1039. this.filteredFolderList = this.visibleFoldersState.filter((folder: FileInfo) => {
  1040. const regex = new RegExp(this.searchText.toLowerCase().replace(/\s+/g, '.*'), 'i');
  1041. return regex.test(folder.fileName?.toLowerCase() ?? "") ||
  1042. regex.test(decodeUrlEncodedString(folder.fileName?.replace('/', '') ?? "").toLowerCase());
  1043. });
  1044. }
  1045. this.updateListData(this.filteredList);
  1046. }
  1047. build() {
  1048. Stack() {
  1049. if (this.accounts.length === 0) {
  1050. this.buildEmptyView();
  1051. } else {
  1052. this.buildContentView();
  1053. }
  1054. // 顶部区域:标题栏在上,面包屑在下
  1055. Column() {
  1056. this.topTitleBar()
  1057. this.breaker()
  1058. }
  1059. .width('100%')
  1060. .visibility(this.isShowTitleBar?Visibility.Visible:
  1061. this.autoHideTitle?Visibility.None:Visibility.Visible)
  1062. .animation({
  1063. duration: 500,
  1064. curve: Curve.Friction // 可选动画曲线
  1065. })
  1066. .position({ top: 0, left: 0 })
  1067. // .backgroundColor($r('app.color.start_window_background'))
  1068. // 多选操作条,位于播放条之上(仅在多选模式下显示)
  1069. if (this.isMultiSelect || this.isDeletingSelection) {
  1070. this.buildSelectionOverlay()
  1071. }
  1072. }
  1073. .width('100%')
  1074. .height('100%')
  1075. .alignContent(Alignment.Bottom)
  1076. .backgroundImage(this.isCustomizeBg?this.customizeBgPath:$r('app.color.start_window_background'))
  1077. .backgroundImageSize(this.isLandscape?{width:'100%'}:{ height: '100%'})
  1078. .backgroundImagePosition(Alignment.Center)
  1079. .backdropBlur(this.blurValue)
  1080. .backgroundBrightness({rate:this.isCustomizeBg?0.1:0,lightUpDegree:this.bgBrightness})
  1081. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  1082. }
  1083. @Builder
  1084. breaker() {
  1085. // 面包屑导航
  1086. Column({ space: 8 }) {
  1087. // 面包屑导航
  1088. if (this.webdavManager.currentPath !== '') {
  1089. Row({ space: 8 }) {
  1090. Button({ type: ButtonType.Circle }) {
  1091. Image(this.webdavManager.canGoBack()?$r('app.media.back'):
  1092. this.selectedAccount.coverPath?this.selectedAccount.coverPath:getCloudDiskIcon(this.selectedAccount.webType))
  1093. .width(15)
  1094. .height(15)
  1095. .borderRadius(10)
  1096. .alt($r('app.media.cloudDisk'))
  1097. .fillColor(Color.White)
  1098. }
  1099. .width(20)
  1100. .height(20)
  1101. .margin({left:5})
  1102. .backgroundColor(this.themeColor)
  1103. .onClick(() => this.goBack())
  1104. Row({ space: 4 }) {
  1105. ForEach(this.breadcrumbs, (crumb: BreadcrumbItem, index: number) => {
  1106. Row() {
  1107. Text(crumb.label)
  1108. .fontSize(15)
  1109. .fontColor($r('app.color.text_color'))
  1110. .maxLines(1)
  1111. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1112. }
  1113. .onClick(() => {
  1114. this.navigateToBreadcrumb(crumb);
  1115. })
  1116. // 添加分隔符(除了最后一个元素)
  1117. if (index < this.breadcrumbs.length - 1) {
  1118. Text('/')
  1119. .fontSize(15)
  1120. .fontColor($r('app.color.index_tab_font_color'))
  1121. .opacity(0.6)
  1122. }
  1123. })
  1124. }
  1125. .layoutWeight(1)
  1126. }
  1127. .width('100%')
  1128. .padding({ left: 4, right: 4 })
  1129. }
  1130. }
  1131. .width('100%')
  1132. .padding({ left: 12, right: 12, top: 8, bottom: 5 })
  1133. }
  1134. // 空状态视图
  1135. @Builder
  1136. buildEmptyView() {
  1137. Column({ space: 20 }) {
  1138. Image($r('app.media.cloudDisk'))
  1139. .width(120)
  1140. .height(120)
  1141. .opacity(0.3)
  1142. Text(`暂无${getRemoteDriveAccountLabel()}`)
  1143. .fontSize(16)
  1144. .fontColor($r('app.color.index_tab_font_color'))
  1145. .opacity(0.6)
  1146. }
  1147. .justifyContent(FlexAlign.Center)
  1148. .width('100%')
  1149. .padding({top: this.topSafeHeight+160})
  1150. .layoutWeight(1)
  1151. }
  1152. // 内容视图
  1153. @Builder
  1154. buildContentView() {
  1155. Column() {
  1156. // 加载状态
  1157. Row() {
  1158. LoadingProgress()
  1159. .width(30)
  1160. .height(30)
  1161. .color(this.themeColor)
  1162. Text('加载中...')
  1163. .fontSize(14)
  1164. .fontColor($r('app.color.index_tab_font_color'))
  1165. .margin({ left: 12 })
  1166. }
  1167. .padding({top: this.topSafeHeight + 90, left: 20, right: 20})
  1168. .visibility(this.isLoading?Visibility.Visible:Visibility.None)
  1169. .opacity(this.isLoading ? 1 : 0)
  1170. .animation({
  1171. duration: 800,
  1172. curve: Curve.Smooth // 可选动画曲线
  1173. })
  1174. // 文件列表(文件夹 + 歌曲)
  1175. if (this.webDavFiles.length > 0) {
  1176. List({ scroller: this.listScroller ,space: 0 }) {
  1177. // 显示文件夹 - 只显示当前目录下的直接子文件夹
  1178. ForEach(this.isSearchMode ? this.filteredFolderList : this.visibleFoldersState, (folder: FileInfo) => {
  1179. ListItem() {
  1180. this.buildFolderItem(folder)
  1181. }
  1182. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  1183. TransitionEffect.scale({ x: 0, y: 0 })))
  1184. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  1185. }, (folder: FileInfo) => folder.name+folder.fileName)
  1186. // 显示歌曲
  1187. LazyForEach(this.dataSource, (song: VideoItem, index: number) => {
  1188. ListItem() {
  1189. this.buildSongItem(song, index)
  1190. }
  1191. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  1192. TransitionEffect.scale({ x: 0, y: 0 })))
  1193. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  1194. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  1195. }
  1196. .scrollBar(BarState.Off)
  1197. .onScrollFrameBegin((offset: number) => {
  1198. // 获取当前滚动偏移量
  1199. if(this.autoHideTitle){
  1200. const currentOffsetY = this.listScroller.currentOffset().yOffset;
  1201. // 判断滚动方向
  1202. if (currentOffsetY > this.prevOffsetY) {
  1203. console.log("onecold 向上滚动");
  1204. this.isShowTitleBar = false
  1205. } else if (currentOffsetY < this.prevOffsetY) {
  1206. console.log("onecold 向下滚动");
  1207. this.isShowTitleBar = true
  1208. }
  1209. // 更新前一次偏移量
  1210. this.prevOffsetY = currentOffsetY;
  1211. }
  1212. return { offsetRemain: offset };
  1213. })
  1214. .contentStartOffset(this.topSafeHeight + 85)
  1215. .contentEndOffset(this.bottomSafeHeight+70)
  1216. .layoutWeight(1)
  1217. .margin({ top: 4 })
  1218. } else if (!this.isLoading) {
  1219. Column() {
  1220. Text('暂无内容')
  1221. .fontSize(14)
  1222. .fontColor($r('app.color.index_tab_font_color'))
  1223. .opacity(0.6)
  1224. Text('点击"左侧菜单"网盘加载')
  1225. .fontSize(12)
  1226. .fontColor($r('app.color.index_tab_font_color'))
  1227. .opacity(0.4)
  1228. .margin({ top: 8 })
  1229. }
  1230. .justifyContent(FlexAlign.Center)
  1231. .layoutWeight(1)
  1232. }
  1233. }
  1234. .layoutWeight(1)
  1235. }
  1236. @Builder
  1237. private buildMultiSelectBar() {
  1238. Row({ space: 12 }) {
  1239. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  1240. .width(55)
  1241. .height(55)
  1242. .fontSize(13)
  1243. .backgroundColor(this.themeColor)
  1244. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1245. .onClick(() => this.toggleSelectAll())
  1246. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  1247. .width(55)
  1248. .height(55)
  1249. .fontSize(13)
  1250. .backgroundColor(this.themeColor)
  1251. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1252. .enabled(this.selectedSongs.length > 0 && !this.isDeletingSelection)
  1253. .onClick(() => this.confirmDeleteSelected())
  1254. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  1255. .width(55)
  1256. .height(55)
  1257. .fontSize(13)
  1258. .backgroundColor(this.themeColor)
  1259. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1260. .onClick(() => this.exitMultiSelect())
  1261. }
  1262. .width('100%')
  1263. .padding({ bottom: 10, top: 12 })
  1264. .justifyContent(FlexAlign.Center)
  1265. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  1266. .opacity(this.isMultiSelect ? 1 : 0)
  1267. .animation({ duration: 300, curve: 'ease-in-out' })
  1268. }
  1269. @Builder
  1270. private buildSelectionOverlay() {
  1271. Column() {
  1272. Row({ space: 10 }) {
  1273. LoadingProgress()
  1274. .width(22)
  1275. .height(22)
  1276. .color(this.themeColor)
  1277. Text('正在删除...')
  1278. .fontSize(14)
  1279. .fontColor($r('app.color.index_tab_font_color'))
  1280. }
  1281. .padding({ top: 12, bottom: 6 })
  1282. .justifyContent(FlexAlign.Center)
  1283. .visibility(this.isDeletingSelection ? Visibility.Visible : Visibility.None)
  1284. this.buildMultiSelectBar()
  1285. }
  1286. .width('100%')
  1287. .padding({ left: 12, right: 12, bottom: this.bottomSafeHeight })
  1288. }
  1289. // 文件夹列表项
  1290. @Builder
  1291. buildFolderItem(folder: FileInfo) {
  1292. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  1293. Row({ space: 2 }) {
  1294. SymbolGlyph($r('sys.symbol.folder'))
  1295. .fontSize(48)
  1296. .fontColor([this.themeColor])
  1297. .alignSelf(ItemAlign.Center)
  1298. .margin({ left: 8, right: 6 })
  1299. // 文件夹信息
  1300. Column({ space: 4 }) {
  1301. Text(decodeUrlEncodedString(folder.fileName.replace('/', '')))
  1302. .fontSize(15)
  1303. .fontColor($r('app.color.index_tab_font_color'))
  1304. .maxLines(1)
  1305. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1306. Text('文件夹')
  1307. .fontSize(13)
  1308. .fontColor($r('app.color.index_tab_font_color'))
  1309. .opacity(0.6)
  1310. }
  1311. .alignItems(HorizontalAlign.Start)
  1312. .layoutWeight(1)
  1313. }
  1314. }
  1315. .reuseId('dir_item')
  1316. .width('100%')
  1317. .padding(12)
  1318. .backgroundColor(Color.Transparent)
  1319. // .backgroundColor($r('app.color.start_window_background'))
  1320. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.8 })
  1321. .onClick(() => {
  1322. this.enterFolder(folder);
  1323. this.breadcrumbs = this.webdavManager.getBreadcrumbs();
  1324. })
  1325. }
  1326. // 歌曲列表项
  1327. @Builder
  1328. buildSongItem(song: VideoItem, index: number) {
  1329. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  1330. Row({ space: 12 }) {
  1331. // 序号
  1332. // 歌曲封面
  1333. Image(song.pixelMapPath ? song.pixelMapPath : $r('app.media.alt'))
  1334. .width(52)
  1335. .height(52)
  1336. .borderRadius(9)
  1337. .sourceSize({width:38, height:38})
  1338. .alt($r('app.media.alt'))
  1339. .fillColor(this.themeColor)
  1340. .objectFit(ImageFit.Cover)
  1341. .shadow({
  1342. radius: StrUtil.isEmpty(song.pixelMapPath) ?6:14,
  1343. type: ShadowType.BLUR,
  1344. color: 'on_primary'
  1345. })
  1346. .margin({ left: 8 })
  1347. .onClick(() => {
  1348. if (this.isMultiSelect) {
  1349. this.toggleSongSelection(song);
  1350. } else {
  1351. this.playSong(song, index, true);
  1352. }
  1353. })
  1354. // 歌曲信息
  1355. Column({ space: 4 }) {
  1356. Text(this.isShowFileName?song.fileName :song.name)
  1357. .fontSize(15)
  1358. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  1359. .fontColor(this.currentSong?.filePath==song.filePath?this.themeColor:$r('app.color.index_tab_font_color'))
  1360. .maxLines(1)
  1361. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1362. Row(){
  1363. Text((song.artist ?? '') + " ")
  1364. .fontSize(13)
  1365. .fontColor(this.currentSong?.filePath==song.filePath?this.themeColor:$r('app.color.index_tab_font_color'))
  1366. .opacity(0.6)
  1367. .maxLines(1)
  1368. .visibility(song.artist?Visibility.Visible:Visibility.None)
  1369. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1370. Text(this.buildSongMetaLine(song))
  1371. .fontSize(13)
  1372. .fontColor(this.currentSong?.filePath==song.filePath?this.themeColor:
  1373. $r('app.color.index_tab_font_color'))
  1374. .opacity(0.6)
  1375. .maxLines(1)
  1376. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1377. }
  1378. .width('90%')
  1379. }
  1380. .alignItems(HorizontalAlign.Start)
  1381. .layoutWeight(1)
  1382. .padding({ right: 20 })
  1383. Column() {
  1384. Checkbox({ name: 'checkbox_' + index })
  1385. .select(this.isSongSelected(song))
  1386. .selectedColor(this.themeColor)
  1387. .opacity(this.isMultiSelect ? 1 : 0)
  1388. .animation({
  1389. duration: 300,
  1390. curve: 'Smooth'
  1391. })
  1392. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  1393. .onChange((checked: boolean) => this.handleCheckboxSelection(song, checked))
  1394. .margin({ left: 10, top: 8, bottom: 8, right: 12 })
  1395. .width(22)
  1396. .height(22)
  1397. ImageAnimator()
  1398. .images(CommonConstants.IMAGE_FRAME_INFO)// 动画数组
  1399. .duration(1000)// 持续
  1400. //.state(this.animationState)// 动画状态
  1401. .state(AnimationStatus.Running)// 动画状态
  1402. .fillMode(FillMode.Forwards)
  1403. .width(18)
  1404. .margin({ right: 12, top: 8, bottom: 8 })
  1405. .visibility(this.currentSong?.filePath==song.filePath ? (this.isMultiSelect ? Visibility.None : Visibility.Visible) :
  1406. Visibility.None)
  1407. .height(18)
  1408. .iterations(-1) // 播放次数
  1409. }
  1410. }
  1411. }
  1412. .width('100%')
  1413. .padding(12)
  1414. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.8 })
  1415. .backgroundColor(Color.Transparent)
  1416. .onClick(() => {
  1417. if (this.isMultiSelect) {
  1418. this.toggleSongSelection(song);
  1419. } else {
  1420. this.playSong(song, index);
  1421. }
  1422. })
  1423. .gesture(LongPressGesture().onAction(() => {
  1424. this.enterMultiSelect(song);
  1425. }))
  1426. }
  1427. // 对话框控制器
  1428. private createFolderDialogController: CustomDialogController | null = null;
  1429. /**
  1430. * 显示创建文件夹对话框
  1431. */
  1432. private showCreateFolderDialog(): void {
  1433. if (!this.selectedAccount) {
  1434. this.getUIContext().getPromptAction().showToast({ message: `请先选择${getRemoteDriveAccountLabel()}` });
  1435. return;
  1436. }
  1437. // 获取当前主题色
  1438. const currentThemeColor = this.themeColor;
  1439. // 创建自定义对话框
  1440. this.createFolderDialogController = new CustomDialogController({
  1441. builder: CreateFolderDialog({
  1442. onConfirm: (folderName: string) => {
  1443. if (folderName.trim().length > 0) {
  1444. void this.createFolder(folderName.trim());
  1445. } else {
  1446. this.getUIContext().getPromptAction().showToast({ message: '文件夹名称不能为空' });
  1447. }
  1448. },
  1449. onCancel: () => {
  1450. // 用户取消创建
  1451. },
  1452. initialName: '',
  1453. themeColor: currentThemeColor
  1454. }),
  1455. autoCancel: true,
  1456. alignment: DialogAlignment.Center,
  1457. customStyle: false
  1458. });
  1459. this.createFolderDialogController.open();
  1460. }
  1461. /**
  1462. * 上传成功后刷新文件列表
  1463. */
  1464. private async refreshFileListAfterUpload(): Promise<void> {
  1465. if (!this.selectedAccount) {
  1466. Logger.warn(TAG, '刷新失败:未选择账户');
  1467. return;
  1468. }
  1469. try {
  1470. Logger.info(TAG, 'heanup 开始刷新上传后的文件列表');
  1471. // 显示加载状态
  1472. this.isLoading = true;
  1473. // 重新加载当前账户的文件信息
  1474. await this.webdavManager.loadFilesInfoFromAccount(this.selectedAccount, this.webdavManager.currentPath);
  1475. // 显示成功提示
  1476. this.getUIContext().getPromptAction().showToast({
  1477. message: '文件上传成功,列表已刷新'
  1478. });
  1479. Logger.info(TAG, 'heanup 文件列表刷新完成');
  1480. } catch (error) {
  1481. const err = error as Error;
  1482. Logger.error(TAG, `heanup 刷新文件列表失败: ${err.message}`);
  1483. // 显示错误提示
  1484. this.getUIContext().getPromptAction().showToast({
  1485. message: `刷新失败: ${err.message}`
  1486. });
  1487. } finally {
  1488. this.isLoading = false;
  1489. }
  1490. }
  1491. /**
  1492. * 创建文件夹的实际方法
  1493. * @param folderName 文件夹名称
  1494. */
  1495. private async createFolder(folderName: string): Promise<void> {
  1496. if (!this.selectedAccount) {
  1497. this.getUIContext().getPromptAction().showToast({ message: `请先选择${getRemoteDriveAccountLabel()}` });
  1498. return;
  1499. }
  1500. if (folderName.length === 0) {
  1501. this.getUIContext().getPromptAction().showToast({ message: '文件夹名称不能为空' });
  1502. return;
  1503. }
  1504. try {
  1505. Logger.info(TAG, `heanup 开始创建文件夹: ${folderName}`);
  1506. // 显示加载状态
  1507. this.isLoading = true;
  1508. if(this.selectedAccount.webType==RemoteDriveType.Baidu){
  1509. // 调用RemoteDriveManager的createBaiduFolder方法
  1510. await this.webdavManager.createBaiduFolder(this.selectedAccount, folderName);
  1511. }else if(this.selectedAccount.webType==RemoteDriveType.WebDav){
  1512. // 调用RemoteDriveManager的createWebDavFolder方法
  1513. await this.webdavManager.createWebDavFolder(this.selectedAccount, folderName);
  1514. }else if(this.selectedAccount.webType==RemoteDriveType.Smb){
  1515. // 调用RemoteDriveManager的createSMBFolder方法
  1516. await this.webdavManager.createSMBFolder(this.selectedAccount, folderName);
  1517. }else if(this.selectedAccount.webType==RemoteDriveType.Ftp){
  1518. // 调用RemoteDriveManager的createFTPFolder方法
  1519. this.getUIContext().getPromptAction().showToast({ message: 'FTP目前不支持创建文件夹' });
  1520. }else{
  1521. this.getUIContext().getPromptAction().showToast({ message: '当前账户类型不支持创建文件夹' });
  1522. }
  1523. // 创建成功后刷新当前目录
  1524. await this.webdavManager.loadFilesInfoFromAccount(this.selectedAccount, this.webdavManager.currentPath);
  1525. this.getUIContext().getPromptAction().showToast({
  1526. message: `文件夹 "${folderName}" 创建成功`
  1527. });
  1528. Logger.info(TAG, `heanup 文件夹创建成功`);
  1529. } catch (error) {
  1530. const err = error as Error;
  1531. Logger.error(TAG, `heanup 创建文件夹失败: ${err.message}`);
  1532. // 显示具体的错误信息
  1533. this.getUIContext().getPromptAction().showToast({
  1534. message: `创建失败: ${err.message}`
  1535. });
  1536. } finally {
  1537. this.isLoading = false;
  1538. }
  1539. }
  1540. }