浏览代码

优化代码

onecold 10 月之前
父节点
当前提交
fdc06ad209

+ 11 - 6
entry/src/main/ets/pages/NewIndex.ets

@@ -1088,10 +1088,15 @@ struct NewIndex {
           }
           // 加载歌单歌曲
           const playlistSongs = await this.playlistTable.queryPlaylistSongs(playlist.id)
-          this.currentSongList = await convertPlaylistSongsToVideoItems(this.context,playlistSongs)
-          this.currentSongListName= playlist.name
-          this.currentSongListID = playlist.id
-          this.modeType = 4//切换到歌单模式
+          if(ArrayUtil.isEmpty(playlistSongs)){
+            this.openPlaylist(playlist)//如果为空进入编辑歌单
+          }else{
+            this.currentSongList = await convertPlaylistSongsToVideoItems(this.context,playlistSongs)
+            this.currentSongListName= playlist.name
+            this.currentSongListID = playlist.id
+            this.modeType = 4//切换到歌单模式
+          }
+
           this.doShowDrawer()
         })
         .bindContextMenu(this.MenuBuilder(playlist), ResponseType.LongPress,
@@ -1245,7 +1250,7 @@ struct NewIndex {
       if (this.playlistTable) {
         const playlists = await this.playlistTable.queryAllPlaylists()
         this.playlistList = playlists
-        console.info(`成功加载 ${playlists.length} 个歌单`)
+        console.info(`onecold 成功加载 ${playlists.length} 个歌单`)
         if(ArrayUtil.isNotEmpty(this.playlistList)){
           const playlistSongs = await this.playlistTable.queryPlaylistSongs(this.playlistList[0].id)
           this.currentSongList = await convertPlaylistSongsToVideoItems(this.context,playlistSongs)
@@ -1254,7 +1259,7 @@ struct NewIndex {
         }
 
       } else {
-        console.warn('歌单表未初始化')
+        console.warn('onecold 歌单表未初始化')
       }
     } catch (error) {
       console.error('加载歌单列表失败:', error)

+ 9 - 4
entry/src/main/ets/pages/PlaylistDetailPage.ets

@@ -1210,11 +1210,16 @@ export async function convertPlaylistSongsToVideoItems(context: Context,playlist
   LogUtil.info(`heanup 开始转换歌曲,共 ${playlistSongs.length} 首`)
 
   const mediaTable: MediaTable = new MediaTable(context)
-  await new Promise<void>((resolve, reject) => {
-    mediaTable.getRdbStore(context,  (err:Error) => {
-      err ? reject(err) : resolve();
+  try {
+    await new Promise<void>((resolve, reject) => {
+      mediaTable.getRdbStore(context,  (err:Error) => {
+        err ? reject(err) : resolve();
+      });
     });
-  });
+  } catch (error) {
+    LogUtil.error(`heanup 数据库连接失败: ${error}`)
+    return [] // 返回空数组而不是崩溃
+  }
   for (const playlistSong of playlistSongs) {
     try {
       LogUtil.info(`heanup 查询歌曲: ${playlistSong.songFilePath}`)

+ 108 - 3
entry/src/main/ets/view/LocalMusic.ets

@@ -165,6 +165,10 @@ export struct LocalMusic {
   @Consume currentSongList: Array<VideoItem>//当前歌单
   @Consume currentSongListName:string //当前歌单名称
   @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
+  @State isRefreshing: boolean = false;
+  @State maxRefreshingHeight: number = 100.0;
+  private contentNode?: ComponentContent<Object> = undefined;
+  @State ratioL: number = 1;
   @State mediaKuCount: number = 0;
   @State albumCount: number = 0;
   @State artistCount: number = 0;
@@ -908,6 +912,7 @@ export struct LocalMusic {
           this.doUpdateData()
           break;
         case 102: //查询媒体库列表
+          this.isRefreshing = false
           this.mediaKuList = e.data.data
           Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
           Utility.doSortListAscending(this.mediaKuList)
@@ -926,6 +931,7 @@ export struct LocalMusic {
           }
           break;
         case 103: //收到查询艺术家列表
+          this.isRefreshing = false
           this.artistMap = e.data.data1;
           this.artistList = e.data.data2;
           PreferencesUtil.putSync('artistCount', this.artistList.length)
@@ -947,6 +953,7 @@ export struct LocalMusic {
           break;
 
         case 104: //收到查询专辑列表
+          this.isRefreshing = false
           this.albumMap = e.data.data1;
 
           this.albumList = e.data.data2
@@ -2268,7 +2275,7 @@ export struct LocalMusic {
                 if(this.isGridMusic){
                   this.getGridView()
                 }else {
-                  this.getListView()
+                  this.getList()
                 }
               }
               if (this.modeType == 0) {
@@ -3081,7 +3088,7 @@ export struct LocalMusic {
 
   private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
   @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
-    buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }],
+    buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
     direction: Direction.Ltr,
     buttonPadding:{top:12,bottom:12},
     backgroundColor: Color.Transparent,
@@ -4782,6 +4789,59 @@ export struct LocalMusic {
     this.pinchValue = 1;
     this.scaleValue = 1;
   }
+
+  @Builder
+  getList(){
+    Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
+      this.getListView()
+    }
+    .pullDownRatio(this.ratioL)
+    .pullToRefresh(true)
+    .refreshOffset(0)
+    .onOffsetChange((offset: number) => {
+      // 越接近最大距离,下拉跟手系数越小。
+      this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
+    })
+    .onStateChange((refreshStatus: RefreshStatus) => {
+      console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
+    })
+    .onRefreshing(async () => {
+      if(this.modeType==0){
+        this.getHistoryList(false)
+        this.asyncCurrentPathOnlyFile()
+      }else if(this.modeType == 1){
+        workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
+      }else if(this.modeType == 2){
+        workerInstance.postMessage({ code: 3, data: this.context });
+      }else if(this.modeType == 3){
+        workerInstance.postMessage({ code: 4, data: this.context });
+      }
+
+
+      console.log('onRefreshing test');
+    })
+
+  }
+
+
+  // 扫描当前目录下的文件,不扫描子目录
+  asyncCurrentPathOnlyFile(){
+    if(this.modeType==0){
+      const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
+        this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
+      taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
+        if(this.modeType==0){
+          this.getSortedFiles(this.currentPath)
+        }
+        setTimeout(() => {
+          this.isRefreshing = false;
+        }, 100)
+      }).catch((e:object)=>{
+        console.info("task1 catch e: " + e);
+      })
+    }
+  }
+
   @Builder
   getListView() {
 
@@ -13325,4 +13385,49 @@ function getFileDirName(filePath: string,rootPath:string): string{
   if(result.startsWith('.'))
     result = result.replace(/\./g, '')
   return result
-}
+}
+
+//只扫描当前目录下文件(不扫描子文件夹)的方法
+@Concurrent
+async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
+  const table: MediaTable = new MediaTable(context);
+
+  try {
+    // 直接获取当前目录下的文件列表
+    const files = FileUtil.listFileSync(dirPath);
+
+    await Promise.all(files.map(async  (file) => {
+      const fPath = `${dirPath}/${file}`;
+
+      // 跳过目录,只处理文件
+      if (FileUtil.isDirectory(fPath))  {
+        return;
+      }
+
+      // 跳过特定格式文件
+      if (fPath.endsWith('.lrc')  || fPath.endsWith('.srt'))  {
+        return;
+      }
+
+      // 检查是否为媒体文件
+      if (Utility.isMeidaByExtension(fPath))  {
+        let mType = CommonConstants.TYPE_LOCAL;
+        if (fPath.includes(lockPath))  {
+          mType = CommonConstants.TYPE_LOCK;
+        }
+
+        const mediaItem = await Utility.uriGetMusicAssetsFromFile(
+          context, fPath, mType, true
+        );
+
+        table.insert(mediaItem,  (id: number) => {
+          // 插入回调函数
+        }, cover_api);
+      }
+    }));
+  } catch (error) {
+    console.error(' 扫描当前目录失败:', error);
+  }
+}
+
+