Kaynağa Gözat

切换webdav账号的实现

onecold 9 ay önce
ebeveyn
işleme
8a5999eca4

+ 60 - 0
entry/src/main/ets/common/util/WebdavManager.ets

@@ -373,6 +373,66 @@ export class WebdavManager {
     }
   }
 
+
+  public async loadFilesInfoFromAccount(account: WebDavAccount,customPath?: string): Promise<void> {
+
+
+    try {
+      this.notifyObservers(WebdavManagerStates.LoadFilesInfoStart);
+
+      // 使用自定义路径或账户默认路径
+      const path = customPath !== undefined ? customPath : account.filepath;
+      this.currentPath = path;
+
+      const files = await this.rcpSocket.getFileList(
+        account.host,
+        account.localHost,
+        account.isUseLocalHost,
+        account.port,
+        path,
+        account.account,
+        account.password,
+        account.enableHttps
+      );
+
+      // 保存所有文件(包括文件夹)
+      // 直接使用从RcpSocketUtil返回的FileInfo对象
+      this.webDavFiles = [];
+      for (let i = 0; i < files.length; i++) {
+        const file = files[i];
+        // 直接添加原始文件对象
+        this.webDavFiles.push(file);
+      }
+
+      // 调试:输出获取到的文件总数
+      Logger.info(TAG, '从WebDAV获取到 ' + files.length + ' 个文件/文件夹');
+
+      // 分别统计文件夹和音频文件
+      let folderCount = 0;
+      let audioCount = 0;
+
+      // 过滤音频文件
+      this.webDavSongs = [];
+      for (let i = 0; i < files.length; i++) {
+        const file = files[i];
+        const fileName = file.fileName;
+
+        if (file.isDirectory) {
+          folderCount++;
+        } else if (this.isAudioFile(fileName)) {
+          audioCount++;
+          const song = this.fileInfoToSong(file, account);
+          this.webDavSongs.push(song);
+        }
+      }
+
+      this.notifyObservers(WebdavManagerStates.LoadFilesInfoSucceed);
+    } catch (error) {
+      this.ErrorMessage = error as BusinessError;
+      this.notifyObservers(WebdavManagerStates.LoadFilesInfoFailed);
+    }
+  }
+
   // 将FileInfo转换为Song
   private fileInfoToSong(fileInfo: FileInfo, account: WebDavAccount): Song {
     const song = new Song(-1, '');

+ 55 - 215
entry/src/main/ets/pages/WebDavMainPage.ets

@@ -54,7 +54,7 @@ function decodeUrlEncodedString(encodedStr: string): string {
 export struct WebDavMainPage {
   @State webdavManager: WebdavManager = WebdavManager.getInstance();
   @State accounts: WebDavAccount[] = [];
-  @State selectedAccount: WebDavAccount | null = null;
+  @Prop @Watch('onSwitchAccount') selectedAccount: WebDavAccount;
   @State songs: Song[] = [];
   @Link mType: number;
   @State isLoading: boolean = false;
@@ -66,6 +66,18 @@ export struct WebDavMainPage {
 
   @State visibleFoldersState: FileInfo[] = []; // 改为普通状态变量
 
+  onSwitchAccount(){
+    console.log('onecold 切换账户:', this.selectedAccount.name);
+    this.songs = [];
+    this.isLoading = true;
+    this.webdavManager.loadFilesInfoFromAccount(this.selectedAccount)
+      .catch((error: Error) => {
+        Logger.error(TAG, '加载文件失败: ' + error.message);
+        this.isLoading = false;
+      });
+    this.breadcrumbs = this.webdavManager.getBreadcrumbs();
+  }
+
   // 更新可见文件夹列表
   private updateVisibleFolders(): void {
     try {
@@ -152,13 +164,13 @@ export struct WebDavMainPage {
         // 更新可见文件夹列表
         this.updateVisibleFolders();
 
-        promptAction.showToast({
-          message: '加载成功: ' + this.webDavFiles.filter(f => f.isDirectory).length + '个文件夹, ' + this.songs.length + '首歌曲'
-        });
+        // promptAction.showToast({
+        //   message: '加载成功: ' + this.webDavFiles.filter(f => f.isDirectory).length + '个文件夹, ' + this.songs.length + '首歌曲'
+        // });
         break;
       case WebdavManagerStates.LoadFilesInfoFailed:
         this.isLoading = false;
-        promptAction.showToast({ message: '加载失败' });
+        this.getUIContext().getPromptAction().showToast({ message: '加载失败' });
         break;
       case WebdavManagerStates.InsertAccountSucceed:
       case WebdavManagerStates.EditAccountSucceed:
@@ -171,15 +183,13 @@ export struct WebDavMainPage {
   // 加载账户列表
   private loadAccounts(): void {
     this.accounts = this.webdavManager.getAllWebDavAccounts();
-    if (this.accounts.length > 0 && !this.selectedAccount) {
-      this.selectedAccount = this.accounts[0];
-    }
+
   }
 
   // 加载文件列表
   private loadFiles(): void {
     if (!this.selectedAccount) {
-      promptAction.showToast({ message: '请先选择账户' });
+      this.getUIContext().getPromptAction().showToast({ message: '请先选择账户' });
       return;
     }
 
@@ -353,22 +363,22 @@ export struct WebDavMainPage {
       emitter.emit(eventPlaylistPlay, eventData);
 
       // 跳转到首页播放器
-      router.pushUrl({
-        url: 'pages/NewIndex',
-        params: {
-          fromWebDAV: true
-        }
-      }).catch((error: Error) => {
-        Logger.error(TAG, '跳转首页失败: ' + error.message);
-        promptAction.showToast({ message: '跳转失败' });
-      });
+      // router.pushUrl({
+      //   url: 'pages/NewIndex',
+      //   params: {
+      //     fromWebDAV: true
+      //   }
+      // }).catch((error: Error) => {
+      //   Logger.error(TAG, '跳转首页失败: ' + error.message);
+      //   this.getUIContext().getPromptAction().showToast({ message: '跳转失败' });
+      // });
     } catch (error) {
       const err = error as Error;
       Logger.error(TAG, '播放歌曲失败: ' + err.message);
-      promptAction.showToast({ message: '播放失败' });
+      this.getUIContext().getPromptAction().showToast({ message: '播放失败' });
     }
   }
-  // 在 WebDavMainPage 类中添加以下方法
+
   // 导航到指定层级的面包屑路径
   private navigateToBreadcrumb(breadcrumbIndex: number): void {
     try {
@@ -526,19 +536,25 @@ export struct WebDavMainPage {
       .margin({ top: 8 })
 
       // 加载状态
-      if (this.isLoading) {
-        Row() {
-          LoadingProgress()
-            .width(30)
-            .height(30)
-            .color(this.themeColor)
-          Text('加载中...')
-            .fontSize(14)
-            .fontColor($r('app.color.index_tab_font_color'))
-            .margin({ left: 12 })
-        }
-        .padding(20)
+
+      Row() {
+        LoadingProgress()
+          .width(30)
+          .height(30)
+          .color(this.themeColor)
+        Text('加载中...')
+          .fontSize(14)
+          .fontColor($r('app.color.index_tab_font_color'))
+          .margin({ left: 12 })
       }
+      .padding(20)
+      .visibility(this.isLoading?Visibility.Visible:Visibility.None)
+      .opacity(this.isLoading ? 1 : 0)
+      .animation({
+        duration: 500,
+        curve: 'ease-in-out' // 可选动画曲线
+      })
+
 
       // 文件列表(文件夹 + 歌曲)
       if (this.webDavFiles.length > 0) {
@@ -619,17 +635,18 @@ export struct WebDavMainPage {
   buildSongItem(song: Song, index: number) {
     Row({ space: 12 }) {
       // 序号
-      Text((index + 1).toString())
-        .fontSize(14)
-        .fontColor($r('app.color.index_tab_font_color'))
-        .opacity(0.6)
-        .width(30)
-        .textAlign(TextAlign.Center)
+      // Text((index + 1).toString())
+      //   .fontSize(14)
+      //   .fontColor($r('app.color.index_tab_font_color'))
+      //   .opacity(0.6)
+      //   .width(30)
+      //   .textAlign(TextAlign.Center)
 
       // 歌曲封面
       Image(song.img)
         .width(48)
         .height(48)
+        .alt($r('app.media.new_music'))
         .borderRadius(4)
         .objectFit(ImageFit.Cover)
 
@@ -666,180 +683,3 @@ export struct WebDavMainPage {
     })
   }
 }
-
-// WebDAV账户对话框
-@CustomDialog
-struct WebDavAccountDialog {
-  controller: CustomDialogController;
-  @Prop isEditMode: boolean = false;
-  @Prop account: WebDavAccount;
-  onConfirm?: (account: WebDavAccount) => void;
-
-  @State accountName: string = '';
-  @State host: string = 'myhome.ss5.xyz';
-  @State port: number = 5005;
-  @State filepath: string = '/';
-  @State username: string = 'chendeben';
-  @State password: string = 'chen384626WYT';
-  @State enableHttps: boolean = false;
-  @StorageProp('themeColor') themeColor: string = CommonConstants.DEFAULT_THEME_COLOR;
-
-  aboutToAppear(): void {
-    this.accountName = this.account.name;
-    this.host = this.account.host;
-    this.port = this.account.port;
-    this.filepath = this.account.filepath;
-    this.username = this.account.account;
-    this.password = this.account.password;
-    this.enableHttps = this.account.enableHttps;
-  }
-
-  build() {
-    Column({ space: 16 }) {
-      // 标题
-      Text(this.isEditMode ? '编辑账户' : '添加账户')
-        .fontSize(18)
-        .fontWeight(FontWeight.Bold)
-        .fontColor($r('app.color.index_tab_font_color'))
-
-      // 账户名称
-      Column({ space: 8 }) {
-        Text('账户名称')
-          .fontSize(14)
-          .fontColor($r('app.color.index_tab_font_color'))
-          .width('100%')
-        TextInput({ placeholder: '请输入账户名称', text: this.accountName })
-          .onChange((value: string) => {
-            this.accountName = value;
-          })
-      }
-      .alignItems(HorizontalAlign.Start)
-
-      // 服务器地址
-      Column({ space: 8 }) {
-        Text('服务器地址')
-          .fontSize(14)
-          .fontColor($r('app.color.index_tab_font_color'))
-          .width('100%')
-        TextInput({ placeholder: '例如: example.com', text: this.host })
-          .onChange((value: string) => {
-            this.host = value;
-          })
-      }
-      .alignItems(HorizontalAlign.Start)
-
-      // 端口
-      Column({ space: 8 }) {
-        Text('端口')
-          .fontSize(14)
-          .fontColor($r('app.color.index_tab_font_color'))
-          .width('100%')
-        TextInput({ placeholder: '默认: 80', text: this.port.toString() })
-          .type(InputType.Number)
-          .onChange((value: string) => {
-            this.port = parseInt(value) || 80;
-          })
-      }
-      .alignItems(HorizontalAlign.Start)
-
-      // 文件目录
-      Column({ space: 8 }) {
-        Text('文件目录')
-          .fontSize(14)
-          .fontColor($r('app.color.index_tab_font_color'))
-          .width('100%')
-        TextInput({ placeholder: '例如: /music', text: this.filepath })
-          .onChange((value: string) => {
-            this.filepath = value;
-          })
-      }
-      .alignItems(HorizontalAlign.Start)
-
-      // 用户名
-      Column({ space: 8 }) {
-        Text('用户名')
-          .fontSize(14)
-          .fontColor($r('app.color.index_tab_font_color'))
-          .width('100%')
-        TextInput({ placeholder: '请输入用户名', text: this.username })
-          .onChange((value: string) => {
-            this.username = value;
-          })
-      }
-      .alignItems(HorizontalAlign.Start)
-
-      // 密码
-      Column({ space: 8 }) {
-        Text('密码')
-          .fontSize(14)
-          .fontColor($r('app.color.index_tab_font_color'))
-          .width('100%')
-        TextInput({ placeholder: '请输入密码', text: this.password })
-          .type(InputType.Password)
-          .onChange((value: string) => {
-            this.password = value;
-          })
-      }
-      .alignItems(HorizontalAlign.Start)
-
-      // HTTPS开关
-      Row() {
-        Text('启用HTTPS')
-          .fontSize(14)
-          .fontColor($r('app.color.index_tab_font_color'))
-        Blank()
-        Toggle({ type: ToggleType.Switch, isOn: this.enableHttps })
-          .selectedColor(this.themeColor)
-          .onChange((isOn: boolean) => {
-            this.enableHttps = isOn;
-          })
-      }
-      .width('100%')
-
-      // 按钮
-      Row({ space: 12 }) {
-        Button('取消', { type: ButtonType.Capsule })
-          .backgroundColor($r('app.color.input_background'))
-          .fontColor($r('app.color.index_tab_font_color'))
-          .layoutWeight(1)
-          .onClick(() => {
-            this.controller.close();
-          })
-
-        Button(this.isEditMode ? '保存' : '添加', { type: ButtonType.Capsule })
-          .backgroundColor(this.themeColor)
-          .layoutWeight(1)
-          .onClick(() => {
-            if (!this.accountName || !this.host) {
-              promptAction.showToast({ message: '请填写账户名称和服务器地址' });
-              return;
-            }
-
-            const updatedAccount = new WebDavAccount();
-            updatedAccount.id = this.account.id;
-            updatedAccount.name = this.accountName;
-            updatedAccount.host = this.host;
-            updatedAccount.port = this.port;
-            updatedAccount.filepath = this.filepath;
-            updatedAccount.account = this.username;
-            updatedAccount.password = this.password;
-            updatedAccount.enableHttps = this.enableHttps;
-            updatedAccount.isActivate = true;
-            updatedAccount.localHost = '';
-            updatedAccount.isUseLocalHost = false;
-            updatedAccount.lyricFilePath = '';
-            updatedAccount.uploadFilePath = '';
-            updatedAccount.imageFilePath = '';
-
-            this.onConfirm?.(updatedAccount);
-            this.controller.close();
-          })
-      }
-      .width('100%')
-      .margin({ top: 8 })
-    }
-    .padding(24)
-    .backgroundColor($r('app.color.start_window_background'))
-    .borderRadius(16)
-  }
-}