Quellcode durchsuchen

更换读取播放历史记录的逻辑,从数据库读取lastPlayedStr字段

onecold vor 1 Jahr
Ursprung
Commit
c2f1c2da29

+ 79 - 0
entry/src/main/ets/common/util/MediaTable.ets

@@ -423,6 +423,85 @@ export default class MediaTable {
     return items;
   }
 
+  // 根据filePath更新lastPlayedStr的值同时playCount值加1
+  public updateLastPlayedStrByFilePath(filePath: string, lastPlayedStr: string, callback: (success: boolean, error?: string) => void) {
+    const predicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
+    predicates.equalTo('filePath',   filePath);
+
+    this.accountTable.query(predicates,   (resultSet: relationalStore.ResultSet) => {
+      if (resultSet.rowCount   === 0) {
+        callback(false, 'Error: File not found');
+        resultSet.close();
+        return;
+      }
+
+      // 获取当前的 playCount 值
+      let currentPlayCount = 0;
+      if (resultSet.goToFirstRow())  {
+        currentPlayCount = resultSet.getLong(resultSet.getColumnIndex('playCount'));
+      }
+
+      resultSet.close();
+
+      // 计算新的 playCount 值
+      const newPlayCount = currentPlayCount + 1;
+
+      // 准备要更新的值
+      const valueBucket: relationalStore.ValuesBucket = {
+        lastPlayedStr: lastPlayedStr,
+        playCount: newPlayCount
+      };
+
+      // 更新数据
+      this.accountTable.updateData(predicates,   valueBucket, (success: boolean) => {
+        callback(success, success ? '' : 'Update failed');
+      });
+    });
+  }
+
+  // 根据最近播放时间查询指定数量的记录
+  public queryRecentPlayedRecords(count: number, callback: (result: VideoItem[]) => void) {
+    try {
+      // 1. 构建查询条件:按lastPlayedStr降序排列,限制返回条数,且lastPlayedStr不为空
+      const predicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
+      // 添加筛选条件,确保lastPlayedStr不为空
+      predicates.isNotNull('lastPlayedStr');
+      predicates.notEqualTo('lastPlayedStr',  ''); // 排除空字符串
+      // 使用 orderByDesc 方法进行降序排序
+      predicates.orderByDesc('lastPlayedStr');
+      // 使用 limit 方法限制返回的记录数量
+      predicates.limitAs(count);
+
+      // 2. 执行查询并处理结果
+      this.accountTable.query(predicates,  (resultSet: relationalStore.ResultSet) => {
+        // 3. 复用已有的解析逻辑
+        const result = this.parseResultSetToVideoItems(resultSet);
+        callback(result);
+      });
+    } catch (err) {
+      Logger.error(`queryRecentPlayedRecords   error: ${err.code}   - ${err.message}`);
+      callback([]);
+    }
+  }
+
+  // 清空播放历史记录
+  public clearPlayHistory(callback: (success: boolean, error?: string) => void) {
+    // 1. 构建查询条件:筛选lastPlayedStr非空的记录
+    const predicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
+    predicates.isNotNull('lastPlayedStr');
+
+    // 2. 准备更新数据:将lastPlayedStr设为空字符串
+    const valueBucket: relationalStore.ValuesBucket = {
+      lastPlayedStr: ''
+    };
+
+    // 3. 执行批量更新操作
+    this.accountTable.updateData(predicates,   valueBucket, (success: boolean) => {
+      // 将 null 替换为 undefined
+      callback(success, success ? 'Clear play history success' : 'Clear play history operation failed');
+    });
+  }
+
   private buildVideoItem(rs: relationalStore.ResultSet): VideoItem {
     // 添加空值保护
     const safeGet = (col: string) => {

+ 44 - 64
entry/src/main/ets/view/LocalMusic.ets

@@ -249,7 +249,6 @@ export struct LocalMusic {
   @Consume isShowDrawer: boolean;
   @Consume offsetX: number;
   @State isFac: boolean = false;
-  @State facList: Array<String> = []
 
   @State favList: Array<VideoItem>= []
   @Consume isFavMusic:boolean
@@ -390,11 +389,8 @@ export struct LocalMusic {
     this.packName = AppUtil.getBundleName()
     this.loadCacheFromStorage(); // 加载缓存
 
-    this.historyList = PreferencesUtil.getSync(LocalMusic.HISTORY_MUSIC, this.historyList) as Array<VideoItem>
-
     this.mkDownLoadDir()
 
-
     let eventMusic: emitter.InnerEvent = { eventId: 2 }
     // 监听广播事件(打开其他应用处理)
     emitter.on(eventMusic, (eventData: emitter.EventData) => {
@@ -570,6 +566,7 @@ export struct LocalMusic {
         workerInstance.postMessage({ code: 2, data: this.context });
         workerInstance.postMessage({ code: 3, data: this.context });
         workerInstance.postMessage({ code: 4, data: this.context });
+        this.getHistoryList(false)
       }
     }, 1000)
 
@@ -589,7 +586,6 @@ export struct LocalMusic {
           if (this.modeType === 1) {
             this.updateListData(this.mediaKuList)
           }
-
           break;
         case 103: //收到查询艺术家列表
           this.artistMap = e.data.data1;
@@ -664,9 +660,6 @@ export struct LocalMusic {
     })
 
 
-    // if (FileUtil.accessSync(this.favPath)) {
-    //   this.facList = FileUtil.listFileSync(this.favPath)
-    // }
     this.getFavList(false)
   }
 
@@ -680,6 +673,21 @@ export struct LocalMusic {
     })
   }
 
+  getHistoryList(isRefresh:boolean){
+    this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
+      this.historyList = result
+      for (let i = 0; i < this.historyList.length; i++) {
+
+        console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
+        console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
+      }
+      if(isRefresh){
+        this.videoLocalList = this.historyList
+        this.updateListData(this.videoLocalList,true)
+      }
+    })
+  }
+
   // 组件消失生命周期
   aboutToDisappear() {
     console.info('LifeCycleComponent aboutToDisappear');
@@ -3482,7 +3490,7 @@ export struct LocalMusic {
           this.titleBarModel.setTitleName('最近播放')
 
           //加载动画效果
-          this.updateListData(this.historyList)
+          this.updateListData(this.historyList,true)
           // this.videoLocalList = this.historyList
 
           if (ArrayUtil.isEmpty(this.historyList)) {
@@ -3547,10 +3555,7 @@ export struct LocalMusic {
           this.currentSong = globalVideoList[this.curIndex]
         }
 
-        if (FileUtil.accessSync(this.favPath)) {
-          this.facList = FileUtil.listFileSync(this.favPath)
-          this.isFac = Utility.getIsFac(this.facList, item)
-        }
+
         this.videoUrl = this.currentSong.filePath
         this.name = this.currentSong.name
         this.cover = this.currentSong.pixelMapPath
@@ -3602,10 +3607,7 @@ export struct LocalMusic {
             this.isShowPlay = true;
             let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
             this.initLyric(lyricPath);
-            if (FileUtil.accessSync(this.favPath)) {
-              this.facList = FileUtil.listFileSync(this.favPath)
-              this.isFac = this.currentPath === this.favPath ? true : Utility.getIsFac(this.facList, this.currentSong)
-            }
+
           } else {
             ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
           }
@@ -6899,7 +6901,7 @@ export struct LocalMusic {
       autoCancel: false, //点击遮障层时,不关闭弹窗
       backCancel: true, //点击返回键,不关闭弹窗
       contentBuilder: () => {
-        this.customTipsBuilder("请到设置界面配置封面服务器地址!")
+        this.customTipsBuilder("请到设置界面配置API服务器地址!")
       },
       buttons: [],
     })
@@ -7806,6 +7808,19 @@ export struct LocalMusic {
     this.setIsPlaying(true)
     this.updateSessionPlayState(true)
     this.watchStatus();
+    this.updateLastPlayTimeStr(this.videoUrl)
+  }
+
+  updateLastPlayTimeStr(filePath:string){
+    let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
+    this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
+      if (success) {
+        this.getHistoryList(false)
+        console.log(" onecold 更新最近播放时间成功,数据库已同步");
+      } else {
+        console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
+      }
+    });
   }
 
   private completionNum(num: number): string | number {
@@ -8044,7 +8059,6 @@ export struct LocalMusic {
 
             this.updateSessionPlayState(true)
             this.setCurrentPlayMode()
-            this.addItemToHistory(this.songList[this.curIndex])
           }, 500)
 
 
@@ -8244,54 +8258,20 @@ export struct LocalMusic {
 
   }
 
-  //添加播放历史记录
-  async addItemToHistory(vItem: VideoItem) {
-    if (vItem.type === CommonConstants.TYPE_LOCK) {
-      return
-    }
-    // 检查是否已存在记录
-    const existingIndex = this.historyList.findIndex(item => item.filePath === vItem.filePath);
-    if (existingIndex !== -1) {
-      // 更新现有记录的播放时间
-      this.historyList[existingIndex].lastPlayed = new Date();
-    } else {
-      // 添加新的播放记录
-      let newItem: VideoItem = new VideoItem(vItem.name, '', vItem.filePath, vItem.type,
-        vItem.videoSize, vItem.cTime, vItem.pixelMap, vItem.size, vItem.pixelMapPath, vItem.artist, vItem.album
-        , vItem.fileName, new Date())
-
-      this.historyList.push(newItem);
+  // 清空播放记录
+  clearVideoHistory() {
+    this.table.clearPlayHistory( (success: boolean, error?: string) => {
+      if (success) {
+        this.historyList = [];
+        this.updateListData(this.historyList)
+        // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
+        ToastUtil.showToast('清空播放记录成功')
 
-    }
-    // 保持播放记录不超过50条
-    if (this.historyList.length > 50) {
-      this.historyList = this.historyList.slice(0, 50);
-    }
-    // 按播放时间降序排序
-    this.historyList.sort((a, b) => {
-      let timeA = a.lastPlayed ? a.lastPlayed.getTime() : 0;
-      let timeB = b.lastPlayed ? b.lastPlayed.getTime() : 0;
-      return timeB - timeA;
+      } else {
+        console.error(" onecold 清空播放记录数据库失败原因: " + error);
+      }
     });
 
-    // 缓存结果
-    PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
-    if (this.isHistory) {
-      this.updateListData(this.historyList)
-    }
-  }
-
-  // 删除播放记录
-  removeVideoFromHistory(path: string) {
-    this.historyList = this.historyList.filter(item => item.filePath !== path);
-  }
-
-  // 清空播放记录
-  clearVideoHistory() {
-    this.historyList = [];
-    this.updateListData(this.historyList)
-    PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
-    ToastUtil.showToast('清空播放记录成功')
 
   }
 

+ 1 - 1
entry/src/main/ets/view/PipLyricTextBuilder.ets

@@ -39,7 +39,7 @@ function buildLyricText(params: Params) {
   .width('100%') // 宽度方向充满画中画窗口
   .height('100%') // 高度方向充满画中画窗口
   .backgroundColor(params.pipBg)
-  .backgroundBlurStyle(BlurStyle.BACKGROUND_REGULAR)
+  .backgroundBlurStyle(BlurStyle.BACKGROUND_THICK)
 }
 
 export  class TextNodeController extends NodeController {

+ 5 - 2
lib/src/main/ets/view/LyricView2.ets

@@ -271,7 +271,6 @@ export struct LyricView2 {
             .fontSize(this.textSize)
             .opacity(this.calculateOpacityFactor(index, this.currentIndex))
             .blur(this.calculateBlurFactor(index, this.currentIndex))
-            .copyOption(CopyOptions.InApp)
             .textAlign(this.alignMode == 'center' ? TextAlign.Center : TextAlign.Start)
             .scale({
                 x: index == this.currentIndex ? this.controller.getHighlightScale() : 1,
@@ -299,7 +298,6 @@ export struct LyricView2 {
                     .margin(0)
                     .opacity(this.calculateOpacityFactor(index, this.currentIndex))
                     .blur(this.calculateBlurFactor(index, this.currentIndex))
-                    .copyOption(CopyOptions.InApp)
                     .animation({
                         // 动画播放速度
                         tempo: 0.8,
@@ -314,6 +312,11 @@ export struct LyricView2 {
         .width(this.alignMode == 'center' ? '100%' : '95%')
     }
 
+
+    isTopBottomLine(index:number){
+        return  index === 0 || index === this.listAdapter.totalCount()  - 1;
+    }
+
     private handleSeekAction() {
         clearTimeout(this.seekUiHideTimeout);
         let targetPosition = this.listAdapter.getData(this.seekIndex).beginTime;