Kaynağa Gözat

修复我的收藏逻辑 由数据库的isFav判断

onecold 1 yıl önce
ebeveyn
işleme
8d96ccbfea

+ 33 - 2
entry/src/main/ets/common/util/MediaTable.ets

@@ -176,6 +176,37 @@ export default class MediaTable {
     });
   }
 
+  // 根据isFav查询数据
+  public queryByisFav(isFav: number, callback: (result: VideoItem[]) => void) {
+    const predicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
+    predicates.equalTo('isFav', isFav);
+
+    this.accountTable.query(predicates, (resultSet: relationalStore.ResultSet) => {
+      const result = this.parseResultSetToVideoItems(resultSet);
+      callback(result);
+    });
+  }
+
+  // 根据filePath更新isFav的值
+  public updateIsFavByFilePath(filePath: string, isFav: number, 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;
+      }
+      resultSet.close();
+
+      const valueBucket: relationalStore.ValuesBucket = { isFav: isFav };
+      this.accountTable.updateData(predicates, valueBucket, (success: boolean) => {
+        callback(success, success ? '' : 'Update failed');
+      });
+    });
+  }
+
   // 查询全部,或者某个id(查询的字段,回调,是否查询全部)
   query(id: number, callback: Function, isAll: boolean = true) {
     let predicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
@@ -355,7 +386,7 @@ export default class MediaTable {
       safeGet('pixelMapPath'),safeGet('artist'),
       safeGet('album'),safeGet('fileName')
     );
-    item.isFav = rs.getDouble(rs.getColumnIndex('videoSize'));
+    item.isFav = rs.getDouble(rs.getColumnIndex('isFav'));
 
 
 
@@ -375,7 +406,7 @@ function generateBucket(item: VideoItem): relationalStore.ValuesBucket {
   obj.videoSize = item.videoSize;
   obj.cTime = item.cTime;
   obj.parentPath = item.parentPath;
-  // obj.isFav = item.isFav;
+  obj.isFav = item.isFav;
 
   // if(item.pixelMapToString){
   //   obj.pixelMapToString = item.pixelMapToString;

+ 15 - 10
entry/src/main/ets/common/util/NetAxiosUtil.ets

@@ -22,6 +22,9 @@ class NetAxiosUtil{
         LogUtil.debug("Heanup 未设置API");
         return ''
       }
+      if(baseUrl.includes(CommonConstants.LRC_API_2)){
+        isApi2 = true
+      }
       let requestUrl = baseUrl
         + '?title=' + encodeURIComponent(title.trim()) + '&artist=' + encodeURIComponent(artist.trim());
 
@@ -30,8 +33,8 @@ class NetAxiosUtil{
       const httpRequest = http.createHttp();
       const options: http.HttpRequestOptions = {
         method: http.RequestMethod.GET,
-        readTimeout: 60000,
-        connectTimeout: 60000,
+        readTimeout: 3000,
+        connectTimeout: 3000,
       };
 
       const response: http.HttpResponse = await httpRequest.request(requestUrl, options);
@@ -65,23 +68,25 @@ class NetAxiosUtil{
 
     try {
       let baseUrl = cover_api
+      LogUtil.debug("onecold getLyricCover baseUrl = "+baseUrl+title+artist);
       if(cover_api===undefined&&StrUtil.isEmpty(cover_api)){
+        LogUtil.debug("onecold getLyricCover baseUrl2 = "+baseUrl);
         baseUrl =  PreferencesUtil.getStringSync('COVER_API','')
-        if ( baseUrl=='') {
-          LogUtil.debug("Heanup 未设置API");
-          return ''
-        }
       }
-
+      LogUtil.debug("onecold getLyricCover baseUrl3 = "+baseUrl);
+      if ( baseUrl=='') {
+        LogUtil.debug("onecold Heanup 未设置API");
+        return ''
+      }
       const cover_url = baseUrl
         + '?title=' + encodeURIComponent(title.trim()) + '&artist=' + encodeURIComponent(artist.trim());
       const httpRequest = http.createHttp();
       const options: http.HttpRequestOptions = {
         method: http.RequestMethod.GET,
-        readTimeout: 60000,
-        connectTimeout: 60000,
+        readTimeout: 3000,
+        connectTimeout: 3000,
       };
-      LogUtil.debug("Heanup 请求封面URL: " + cover_url);
+      LogUtil.debug("onecold Heanup 请求封面URL: " + cover_url);
       const response: http.HttpResponse = await httpRequest.request(cover_url, options);
       if (response.responseCode === 200) {
         const res = response.result as string;

+ 2 - 2
entry/src/main/ets/common/util/RdbUtils.ets

@@ -134,9 +134,9 @@ export default class RdbUtils {
                 const updateValues: relationalStore.ValuesBucket = { pixelMapPath: newPixelMapPath };
                 this.updateData(predicates, updateValues, (updateSuccess: boolean) => {
                   if (updateSuccess) {
-                    Logger.info(RdbUtils.RDB_TAG, `Updated pixelMapPath for id ${id}.`);
+                    Logger.info(RdbUtils.RDB_TAG, `onecold Updated pixelMapPath for id ${id}.`);
                   } else {
-                    Logger.error(RdbUtils.RDB_TAG, `Failed to update pixelMapPath for id ${id}.`);
+                    Logger.error(RdbUtils.RDB_TAG, `onecold Failed to update pixelMapPath for id ${id}.`);
                   }
                   callback(updateSuccess);
                 });

+ 3 - 1
entry/src/main/ets/pages/NewIndex.ets

@@ -61,6 +61,8 @@ struct NewIndex{
   @Provide('isMusicZero') isMusicZero:boolean = false;
   /** 本地音乐列表,持久化存储 */
   @StorageLink('musicLocalList')  musicLocalList: Array<VideoItem> = []
+
+  @Provide isFavMusic:boolean =  false
   /** 标题栏配置模型 */
   @State titleBarModel: TitleBar.Model = new TitleBar.Model()
     .setTitleTextStyle(FontStyle.Normal)
@@ -115,7 +117,7 @@ struct NewIndex{
    * - 如果是根目录,双击返回键退出应用,否则提示
    */
   onBackPress(): boolean | void {
-    if(this.currentPath !== this.rootPath||this.isHistory||(this.modeType!==0&&this.isCanBack)){
+    if(this.currentPath !== this.rootPath||this.isHistory||this.isFavMusic||(this.modeType!==0&&this.isCanBack)){
       const eventData: emitter.EventData = {};
       emitter.emit({ eventId: 888 }, eventData); // 发送音频广播通知更新doSwipBack
     }else{

+ 75 - 83
entry/src/main/ets/view/LocalMusic.ets

@@ -168,6 +168,7 @@ export struct LocalMusic {
   @State sortType: number = 4 //默认排序方式
 
   onModeChange() {
+    this.isFavMusic = false
     if (this.modeType === 2 || this.modeType === 3) {
       this.titleBarModel.setRightIcon(null)
     } else {
@@ -212,6 +213,9 @@ export struct LocalMusic {
   @Consume offsetX: number;
   @State isFac: boolean = false;
   @State facList: Array<String> = []
+
+  @State favList: Array<VideoItem>= []
+  @Consume isFavMusic:boolean
   @State isClickedPLayAll: boolean = false;
   private scrollerForlist: ListScroller = new ListScroller();
   imagesF: ImageFrameInfo[] = [
@@ -324,7 +328,7 @@ export struct LocalMusic {
       return
     }
 
-    if (this.isHistory) {
+    if (this.isHistory||this.isFavMusic) {
       this.isHistory = false
       this.getSortedFiles(this.currentPath)
       return
@@ -524,6 +528,7 @@ export struct LocalMusic {
     }
 
     this.getSortedFiles(this.rootPath).then(() => {
+      this.isFavMusic = false
       //穿山甲
       this.loadBannerAd(CSJUtil.getBannerID())
 
@@ -552,10 +557,20 @@ export struct LocalMusic {
     })
 
 
-    if (FileUtil.accessSync(this.favPath)) {
-      this.facList = FileUtil.listFileSync(this.favPath)
-    }
+    // if (FileUtil.accessSync(this.favPath)) {
+    //   this.facList = FileUtil.listFileSync(this.favPath)
+    // }
+    this.getFavList(false)
+  }
 
+  getFavList(isFavRefresh:boolean){
+    this.table.queryByisFav(1, async (result: VideoItem[]) => {
+      this.favList = result
+      if(isFavRefresh||this.isFavMusic){//如果是我的收藏,更新我的收藏数据
+        this.videoLocalList = this.favList
+        this.updateListData(this.videoLocalList)
+      }
+    })
   }
 
   // 组件消失生命周期
@@ -574,6 +589,7 @@ export struct LocalMusic {
   }
 
   async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
+    this.isFavMusic = false
     if (isWorkerPost) {
       workerInstance.postMessage({ code: 2, data: this.context }); //刷新媒体库列表
     }
@@ -685,7 +701,7 @@ export struct LocalMusic {
       console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
       // for (let i = 0; i < this.videoLocalList.length; i++) {
       //
-      //   console.info(`onecold gengxin 1: ${this.videoLocalList[i].name}`);
+      //   console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
       //
       // }
 
@@ -1755,6 +1771,7 @@ export struct LocalMusic {
               .width('35%')
               .height(60)
               .margin({ top: 10, bottom: 10, right: 6 })
+              .visibility(this.isFavMusic?Visibility.None:Visibility.Visible)
               .backgroundColor($r('app.color.title_bar_bg'))
               .onClick(() => {
                 this.showWarnIsDelete()
@@ -1953,51 +1970,37 @@ export struct LocalMusic {
       .show();
   }
 
-  //加入收藏
-  addFac(item: VideoItem) {
-    const newPath = this.favPath + '/' + item.fileName;
-    FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
-      let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
-        CommonConstants.TYPE_LOCAL, true);
-      this.table.insert(newItem, (id: number) => {
-        //加入数据库
-      });
-      ToastUtil.showToast('收藏成功');
-      this.cache.delete(this.favPath); // 删除目标路径缓存
-      if (FileUtil.accessSync(this.favPath)) {
-        this.facList = FileUtil.listFileSync(this.favPath)
-        this.isFac = Utility.getIsFac(this.facList, item)
-      }
+  doFav(item:VideoItem){
+    LogUtil.info('onecold doFav isFav=' +item.isFav)
 
-    }).catch((error: Error) => {
-      console.error(error.message);
-    });
-  }
+    let isFav = 0
+    if(Utility.getIsFav(this.favList,item)){
+      isFav = 0
+    }else{
+      isFav = 1
+    }
 
-  //取消收藏
-  async cancelFac(item: VideoItem) {
-    const newPath = this.favPath + '/' + item.fileName;
-    let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
-      CommonConstants.TYPE_LOCAL, true);
-    this.table.deleteData(newItem, () => {
-      FileUtil.unlink(newPath).then(() => {
-        ToastUtil.showToast('取消收藏成功');
-        this.cache.delete(this.favPath); // 删除目标路径缓存
-        if (FileUtil.accessSync(this.favPath)) {
-          this.facList = FileUtil.listFileSync(this.favPath)
-          this.isFac = Utility.getIsFac(this.facList, item)
+    this.table.updateIsFavByFilePath(item.filePath,isFav, async (result: boolean) => {
+      if(result){
+        if(isFav===1){
+          ToastUtil.showToast('收藏成功');
+        }else{
+          ToastUtil.showToast('取消收藏成功');
         }
-        if (this.currentPath === this.favPath) {
-          this.getSortedFiles(this.favPath)
+        this.deleteCache(this.currentPath)
+        this.getFavList(false)
+        if(this.modeType===0&&!this.isFavMusic){
+          LogUtil.info('onecold doFav currentPath ='+ this.currentPath)
+          this.getSortedFiles(this.currentPath)
         }
-
-      }).catch((error: Error) => {
-        console.error(error.message);
-      });
-    });
+        workerInstance.postMessage({ code: 2, data: this.context });
+        workerInstance.postMessage({ code: 3, data: this.context });
+        workerInstance.postMessage({ code: 4, data: this.context });
+      }
+    })
+  }
 
 
-  }
 
   //多选复制文件
   showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
@@ -2468,8 +2471,12 @@ export struct LocalMusic {
           })// .opacity(this.opacityItem)
           .clickEffect({ level: ClickEffectLevel.MIDDLE })
           .onClick(() => {
-            this.deleteCache(this.currentPath)
-            this.getSortedFiles(this.currentPath)
+            if(this.isFavMusic){
+              this.getFavList(true)
+            }else{
+              this.deleteCache(this.currentPath)
+              this.getSortedFiles(this.currentPath)
+            }
           })
 
         Image($r("app.media.top_rank"))
@@ -2832,7 +2839,16 @@ export struct LocalMusic {
           }
           this.isHistory = true
           this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
-        } else {
+        } else if(item.name === LocalMusic.STR_FAC_VIDEO){
+          this.titleBarModel.setTitleName('我的收藏')
+          //加载动画效果
+          this.updateListData(this.favList)
+          if(ArrayUtil.isEmpty(this.favList)){
+            ToastUtil.showToast('无音乐收藏记录')
+          }
+          this.isFavMusic = true
+          this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
+        }else {
           this.currentPath = item.filePath
           this.getSortedFiles(this.currentPath)
         }
@@ -4827,19 +4843,13 @@ export struct LocalMusic {
 
             })
           //添加或取消收藏
-          Image(this.isFac ? $r('app.media.add_fac_light') : $r('app.media.add_fac'))
+          Image(Utility.getIsFav(this.favList,this.currentSong)?$r('app.media.add_fac_light'):$r('app.media.add_fac'))
             .width(24)
             .aspectRatio(CommonConstants.ASPECT_RATIO)
             .onClick(async () => {
-              if (this.currentSong) {
-                if (this.isFac) {
-                  this.cancelFac(this.currentSong)
-                } else {
-                  this.addFac(this.currentSong)
-                }
+              if(this.currentSong){
+                this.doFav(this.currentSong)
               }
-
-
             })
         }
         .margin({ right: 33 })
@@ -4950,7 +4960,7 @@ export struct LocalMusic {
       // .visibility(this.isHide?Visibility.Hidden:Visibility.Visible)
 
     }
-    .position({ bottom: 30 }) // 将  固定在底部
+    .position({ bottom: 55 }) // 将  固定在底部
 
   }
 
@@ -5024,7 +5034,7 @@ export struct LocalMusic {
         // 唱针以左上角为点选择逆时针40度
         Image($r('app.media.ic_music_cover_hand'))
           .height(130)
-          .margin({ bottom: 180, top: 10 })
+          .margin({ bottom: 220, top: 0 })
           .align(Alignment.Top)
           .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
           .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
@@ -6870,7 +6880,7 @@ export struct LocalMusic {
     // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
     let playBState: avSession.AVPlaybackState = {
       loopMode: mLoopMode,
-      // isFavorite:Utility.getIsFav(this.favList,this.currentSong),
+      isFavorite:Utility.getIsFav(this.favList,this.currentSong),
     };
     this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
       console.info(`set setLoopMode AVPlaybackState successfully`);
@@ -6884,19 +6894,11 @@ export struct LocalMusic {
       console.info(`on toggleFavorite `);
       // 应用收到收藏命令,进行收藏处理。
 
-      if (FileUtil.accessSync(this.favPath)) {
-        this.facList = FileUtil.listFileSync(this.favPath)
-        this.isFac = Utility.getIsFac(this.facList, this.currentSong)
-      }
-
-      if (this.isFac) {
-        this.cancelFac(this.currentSong)
-      } else {
-        this.addFac(this.currentSong)
-      }
+      this.isFac = Utility.getIsFav(this.favList,this.currentSong)
+      this.doFav(this.currentSong)
       // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
       let playbackState: avSession.AVPlaybackState = {
-        isFavorite: !this.isFac,
+        isFavorite:!this.isFac,
       };
       this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
         console.info(`SetAVPlaybackState successfully`);
@@ -7549,7 +7551,7 @@ export struct LocalMusic {
     Row() {
       //加入收藏
       Button() {
-        Image(Utility.getIsFac(this.facList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
+        Image(Utility.getIsFav(this.favList,item)?$r('app.media.add_fac_light2'):$r('app.media.add_fac'))
           .fillColor(Color.White)
           .width(20)
       }
@@ -7560,18 +7562,8 @@ export struct LocalMusic {
       .margin(5)
       .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
       .onClick(() => {
-        if (item) {
-          if (FileUtil.accessSync(this.favPath)) {
-            this.facList = FileUtil.listFileSync(this.favPath)
-
-            this.isFac = Utility.getIsFac(this.facList, item)
-          }
-
-          if (this.isFac) {
-            this.cancelFac(item)
-          } else {
-            this.addFac(item)
-          }
+        if(item){
+          this.doFav(item)
         }
       })