chendeben 7 месяцев назад
Родитель
Сommit
ee474d63e3
2 измененных файлов с 136 добавлено и 60 удалено
  1. 76 45
      entry/src/main/ets/view/LocalMusic.ets
  2. 60 15
      entry/src/main/ets/workers/Worker.ets

+ 76 - 45
entry/src/main/ets/view/LocalMusic.ets

@@ -184,6 +184,49 @@ export interface WorkerMetadataPayload {
   error?: string;
 }
 
+interface WorkerMessageScanDone {
+  code: 101;
+  data: Record<string, never>;
+}
+
+interface WorkerMessageMediaList {
+  code: 102;
+  data: Array<VideoItem>;
+  totalCount: number;
+}
+
+interface WorkerMessageArtistList {
+  code: 103;
+  data1: Map<string, Array<VideoItem>>;
+  data2: Array<VideoItem>;
+  totalCount: number;
+}
+
+interface WorkerMessageAlbumList {
+  code: 104;
+  data1: Map<string, Array<VideoItem>>;
+  data2: Array<VideoItem>;
+  totalCount: number;
+}
+
+interface WorkerMessageMetadata {
+  code: 105;
+  data: WorkerMetadataPayload;
+}
+
+interface WorkerMessageEditResult {
+  code: 106;
+  data: WorkerEditMusicResult;
+}
+
+type LocalMusicWorkerMessage =
+  WorkerMessageScanDone
+  | WorkerMessageMediaList
+  | WorkerMessageArtistList
+  | WorkerMessageAlbumList
+  | WorkerMessageMetadata
+  | WorkerMessageEditResult;
+
 /**
  * 歌单播放事件数据
  */
@@ -1139,8 +1182,8 @@ export struct LocalMusic {
 
 
     workerInstance.onmessage = (e: MessageEvents): void => {
-
-      switch (e.data.code) {
+      const message = e.data as LocalMusicWorkerMessage;
+      switch (message.code) {
         case 101: //第一次扫描文件夹入库
           ToastUtil.showToast('刷新同步数据库成功!')
           Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
@@ -1148,56 +1191,50 @@ export struct LocalMusic {
           break;
         case 102: //查询媒体库列表
           this.isRefreshing = false
-          this.mediaKuList = e.data.data
-          Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
+          this.mediaKuList = message.data  // 只包含前100条
+          const mediaTotalCount: number = message.totalCount ?? this.mediaKuList.length;
+          this.mediaKuCount = mediaTotalCount;
+          Logger.info(`heanup 查询媒体库列表 缓存数=${this.mediaKuList.length}, 总数=${mediaTotalCount}`)
           Utility.doSortListAscending(this.mediaKuList)
           AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
           // 媒体库模式下重新加载第一页(分页查询)
           if (this.modeType === 1) {
             this.resetAndLoadFirstPage();
           }
-          PreferencesUtil.putSync('mediaKuCount', this.mediaKuList.length)
-          // 处理媒体库前100条记录,列表长度并存储到PreferencesUtil
-          if (ArrayUtil.isNotEmpty(this.mediaKuList)&&this.mediaKuList.length  > 100) {
-            // 只保存前100条记录到缓存中
-            let truncatedList = this.mediaKuList.slice(0,  100);
-            PreferencesUtil.putSync('mediaKuList',  JSON.stringify(truncatedList));
-          } else {
-            PreferencesUtil.putSync('mediaKuList',  JSON.stringify(this.mediaKuList));
-          }
+          PreferencesUtil.putSync('mediaKuCount', mediaTotalCount)
+          // 只保存前100条记录到缓存中
+          PreferencesUtil.putSync('mediaKuList',  JSON.stringify(this.mediaKuList));
           break;
         case 103: //收到查询艺术家列表
           this.isRefreshing = false
-          this.artistMap = e.data.data1;
-          this.artistList = e.data.data2;
-          PreferencesUtil.putSync('artistCount', this.artistList.length)
+          this.artistMap = message.data1;  // 只包含前60个艺术家的歌曲
+          this.artistList = message.data2; // 只包含前100个艺术家
+          const artistTotalCount: number = message.totalCount ?? this.artistList.length;
+          this.artistCount = artistTotalCount;
+          Logger.info(`heanup 查询艺术家列表 缓存数=${this.artistList.length}, 总数=${artistTotalCount}`)
+          PreferencesUtil.putSync('artistCount', artistTotalCount)
 
           // 艺术家模式下重新加载第一页(分页查询)
           if (this.modeType === 2) {
             this.resetAndLoadFirstPage();
           }
 
-          // 处理艺术家前100条记录,列表长度并存储到PreferencesUtil
-          if (ArrayUtil.isNotEmpty(this.artistList)&&this.artistList.length  > 100) {
-            // 只保存前100条记录到缓存中
-            let truncatedList = this.artistList.slice(0,  100);
-            PreferencesUtil.putSync('artistList',  JSON.stringify(truncatedList));
-          } else {
-            PreferencesUtil.putSync('artistList',  JSON.stringify(this.artistList));
-          }
-          // 处理并缓存前60条艺术家数据
-          const sortedEntries = Array.from(this.artistMap.entries())
-            .sort((a, b) => b[1].length - a[1].length)
-            .slice(0, 60);
-
+          // 保存前100条艺术家列表
+          PreferencesUtil.putSync('artistList',  JSON.stringify(this.artistList));
+          
+          // 保存前60条艺术家的歌曲Map
+          const sortedEntries = Array.from(this.artistMap.entries());
           PreferencesUtil.putSync('artistMap',  JSON.stringify(sortedEntries));
           break;
 
         case 104: //收到查询专辑列表
           this.isRefreshing = false
-          this.albumMap = e.data.data1;
+          this.albumMap = message.data1;
 
-          this.albumList = e.data.data2
+          this.albumList = message.data2
+          const albumTotalCount: number = message.totalCount ?? this.albumList.length;
+          this.albumCount = albumTotalCount;
+          Logger.info(`heanup 查询专辑列表 缓存数=${this.albumList.length}, 总数=${albumTotalCount}`)
           
           // 专辑模式下重新加载第一页(分页查询)
           if (this.modeType === 3) {
@@ -1210,25 +1247,19 @@ export struct LocalMusic {
             console.info('onecold startPlayOrResumePlay 757')
             this.startPlayOrResumePlay()
           }
-          PreferencesUtil.putSync('albumCount', this.albumList.length)
-          // 处理专辑前100条记录,列表长度并存储到PreferencesUtil
-          if (ArrayUtil.isNotEmpty(this.albumList)&&this.albumList.length  > 100) {
-            // 只保存前100条记录到缓存中
-            let truncatedList = this.albumList.slice(0,  100);
-            PreferencesUtil.putSync('albumList',  JSON.stringify(truncatedList));
-          } else {
-            PreferencesUtil.putSync('albumList',  JSON.stringify(this.albumList));
-          }
-          const mapArrayAlbum = Array.from(this.albumMap.entries())
-            .sort((a, b) => b[1].length - a[1].length)
-            .slice(0, 60);
+          PreferencesUtil.putSync('albumCount', albumTotalCount)
+          // 保存前100条专辑列表(Worker已经只发送了100条)
+          PreferencesUtil.putSync('albumList',  JSON.stringify(this.albumList));
+          
+          // 保存前60条专辑Map(Worker已经只发送了60条)
+          const mapArrayAlbum = Array.from(this.albumMap.entries());
           PreferencesUtil.putSync('albumMap',  JSON.stringify(mapArrayAlbum));
           break;
         case 105: // 缓存完成后返回的元数据
-          this.handleWorkerMetadataPayload(e.data.data as WorkerMetadataPayload);
+          this.handleWorkerMetadataPayload(message.data);
           break;
         case 106: // 编辑音乐元数据和封面完成
-          this.handleEditMusicResult(e.data);
+          this.handleEditMusicResult(message.data);
           break;
 
       }

+ 60 - 15
entry/src/main/ets/workers/Worker.ets

@@ -154,6 +154,7 @@ async function scanDirectory(context: Context, curPath: string, lockPath: string
 
 
 //获取当前媒体库歌曲列表
+// 优化:不再加载全部数据,只返回统计信息和前100条缓存数据
 async function queryMediaKuList(context: Context,packageName: string) {
   const table: MediaTable = new MediaTable(context);
   try {
@@ -164,7 +165,7 @@ async function queryMediaKuList(context: Context,packageName: string) {
       });
     });
 
-    // 2. 查询媒体库(isVideo=1)音乐
+    // 2. 查询媒体库(isVideo=1)音乐 - 只获取前100条用于缓存
     const originalList: VideoItem[] = await new Promise((resolve, reject) => {
       table.query(0,  (result: VideoItem[] | null, err?: Error) => {
         if (err) {
@@ -174,10 +175,18 @@ async function queryMediaKuList(context: Context,packageName: string) {
         }
       });
     });
-    workerPort.postMessage({  code: 102, data: originalList });
-    // 3. 并行校验文件有效性
+    
+    // 获取总数但不发送完整列表
+    const totalCount = originalList.length;
+    Logger.info(`heanup Worker queryMediaKuList: 总歌曲数=${totalCount}`);
+    
+    // 只发送前100条用于缓存和快速显示
+    const cachedList = originalList.slice(0, 100);
+    workerPort.postMessage({  code: 102, data: cachedList, totalCount: totalCount });
+    
+    // 3. 并行校验文件有效性 - 只校验前100条
     const validList = await Promise.all(
-      originalList.map(async  item => {
+      cachedList.map(async  item => {
         try {
           const exists = await FileUtil.access(item.filePath);  // 改为异步校验
           if (exists||!(item.filePath.includes(packageName))) return item;//如果不是本DownLoad目录下包名文件,不能删除
@@ -198,8 +207,8 @@ async function queryMediaKuList(context: Context,packageName: string) {
 
     // 4. 过滤已删除项并返回结果
     const finalList = validList.filter(Boolean)  as VideoItem[];
-    if(originalList&&finalList&&originalList.length!=finalList.length){
-      workerPort.postMessage({  code: 102, data: finalList });
+    if(cachedList&&finalList&&cachedList.length!=finalList.length){
+      workerPort.postMessage({  code: 102, data: finalList, totalCount: finalList.length });
     }
 
   }catch (err) {
@@ -219,11 +228,11 @@ async function  queryArtistTask(context:Context) {
 
       console.log(` onecold testtag queryArtistTask:`);
       table.queryArtistsWithSongs((resultMap:  Map<string, VideoItem[]>) => {
-        let artistMap:Map<string, VideoItem[]> = new Map();
-        artistMap = resultMap
+        // 不再保存完整的artistMap到内存,只生成艺术家列表
         let artistList:Array<VideoItem> = []
-        console.log(` onecold testtag 当前艺术家数量:${artistMap.size}`);
-        artistMap.forEach((songs,  artist) => {
+        console.log(` onecold testtag 当前艺术家数量:${resultMap.size}`);
+        
+        resultMap.forEach((songs,  artist) => {
           let item = new VideoItem(artist,artist,artist,CommonConstants.TYPE_IS_ARTIST,0,'')
           // 新增遍历逻辑
           let targetPixelMap: string | null = null;
@@ -238,14 +247,32 @@ async function  queryArtistTask(context:Context) {
           // console.log(` onecold testtag 艺术家:${artist}`);
           artistList.push(item)
         });
+        
         // 核心排序逻辑
         artistList.sort((a,  b) => {
-          const countA = artistMap.get(a.name)?.length  || 0;
-          const countB = artistMap.get(b.name)?.length  || 0;
+          const countA = resultMap.get(a.name)?.length  || 0;
+          const countB = resultMap.get(b.name)?.length  || 0;
           return countB - countA; // 商量降序排列
         });
 
-        workerPort.postMessage({ code: 103, data1: artistMap,data2:artistList }); // 返回主线程
+        // 只保存前60条艺术家的歌曲Map用于缓存
+        const topArtists = artistList.slice(0, 60);
+        const cachedArtistMap = new Map<string, VideoItem[]>();
+        topArtists.forEach(artist => {
+          const songs = resultMap.get(artist.name);
+          if (songs) {
+            cachedArtistMap.set(artist.name, songs);
+          }
+        });
+
+        // 只发送前100条艺术家列表和前60条的Map
+        const cachedArtistList = artistList.slice(0, 100);
+        workerPort.postMessage({ 
+          code: 103, 
+          data1: cachedArtistMap,  // 只包含前60个艺术家的歌曲
+          data2: cachedArtistList, // 只包含前100个艺术家
+          totalCount: artistList.length  // 总艺术家数量
+        });
 
       });
 
@@ -294,13 +321,31 @@ async function queryAlbumTask(context:Context) {
         const bCount = resultMap.get(b.name)?.length || 0;
         return bCount - aCount;
       });
-      workerPort.postMessage({ code: 104, data1: resultMap,data2:albumList }); // 返回主线程
+      
+      // 只保存前60条专辑的歌曲Map用于缓存
+      const topAlbums = albumList.slice(0, 60);
+      const cachedAlbumMap = new Map<string, VideoItem[]>();
+      topAlbums.forEach(album => {
+        const songs = resultMap.get(album.name);
+        if (songs) {
+          cachedAlbumMap.set(album.name, songs);
+        }
+      });
+
+      // 只发送前100条专辑列表和前60条的Map
+      const cachedAlbumList = albumList.slice(0, 100);
+      workerPort.postMessage({ 
+        code: 104, 
+        data1: cachedAlbumMap,   // 只包含前60个专辑的歌曲
+        data2: cachedAlbumList,  // 只包含前100个专辑
+        totalCount: albumList.length  // 总专辑数量
+      });
 
 
     });
 
   }catch (err) {
-    Logger.error(` onecold testtag queryArtistTask: ${err.code}  - ${err.message}`);
+    Logger.error(` onecold testtag queryAlbumTask: ${err.code}  - ${err.message}`);
 
   }
 }