MediaTable.ets 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. import relationalStore from '@ohos.data.relationalStore';
  2. import { StrUtil } from '@pura/harmony-utils';
  3. import { VideoItem } from '../../viewmodel/VideoItem';
  4. import Logger from './Logger';
  5. import RdbUtils from './RdbUtils';
  6. import { Utility } from './Utility';
  7. /**
  8. * 数据库字段常量接口定义
  9. */
  10. interface DBColumnsInterface {
  11. ID: string;
  12. NAME: string;
  13. FILE_PATH: string;
  14. TYPE: string;
  15. VIDEO_SIZE: string;
  16. C_TIME: string;
  17. PARENT_PATH: string;
  18. IS_FAV: string;
  19. PIXEL_MAP_PATH: string;
  20. ARTIST: string;
  21. ALBUM: string;
  22. FILE_NAME: string;
  23. SIZE: string;
  24. DURATION: string;
  25. MIME_TYPE: string;
  26. TRACK_COUNT: string;
  27. SAMPLE_RATE: string;
  28. LAST_PLAYED_STR: string;
  29. PLAY_COUNT: string;
  30. LYRIC_CONTENT: string;
  31. }
  32. /**
  33. * 数据库字段常量,避免硬编码
  34. */
  35. const DB_COLUMNS: DBColumnsInterface = {
  36. ID: 'id',
  37. NAME: 'name',
  38. FILE_PATH: 'filePath',
  39. TYPE: 'mtype',
  40. VIDEO_SIZE: 'videoSize',
  41. C_TIME: 'cTime',
  42. PARENT_PATH: 'parentPath',
  43. IS_FAV: 'isFav',
  44. PIXEL_MAP_PATH: 'pixelMapPath',
  45. ARTIST: 'artist',
  46. ALBUM: 'album',
  47. FILE_NAME: 'fileName',
  48. SIZE: 'size',
  49. DURATION: 'duration',
  50. MIME_TYPE: 'mimeType',
  51. TRACK_COUNT: 'trackCount',
  52. SAMPLE_RATE: 'sampleRate',
  53. LAST_PLAYED_STR: 'lastPlayedStr',
  54. PLAY_COUNT: 'playCount',
  55. LYRIC_CONTENT: 'lyricContent'
  56. };
  57. export default class MediaTable {
  58. private accountTable = new RdbUtils(RdbUtils.MEDIA_TABLE.tableName, RdbUtils.MEDIA_TABLE.sqlCreate,
  59. RdbUtils.MEDIA_TABLE.columns);
  60. constructor(context:Context,callback: Function = () => {
  61. }) {
  62. this.accountTable.getRdbStore(context,callback);
  63. }
  64. getRdbStore(context:Context,callback: Function = () => {
  65. }) {
  66. this.accountTable.getRdbStore(context,callback);
  67. }
  68. insert(item: VideoItem, callback: Function,cover_api?:string) {
  69. const valueBucket: relationalStore.ValuesBucket = generateBucket(item);
  70. this.accountTable.insertData(valueBucket, callback,cover_api);
  71. }
  72. deleteData(item: VideoItem, callback: Function) {
  73. let predicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
  74. predicates.equalTo('id', item.id);
  75. this.accountTable.deleteData(predicates, callback);
  76. }
  77. deleteDataForParentPath(parentPath:string, callback: Function) {
  78. let predicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
  79. predicates.equalTo('parentPath', parentPath);
  80. this.accountTable.deleteData(predicates, callback);
  81. }
  82. public updatePixelMapPath(filePath: string, newPixelMapPath: string, callback: Function) {
  83. // Step 1: 构建查询条件验证文件存在性
  84. const queryPredicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
  85. queryPredicates.equalTo('filePath', filePath);
  86. // Step 2: 执行存在性验证
  87. this.accountTable.query(queryPredicates, (resultSet: relationalStore.ResultSet) => {
  88. if (resultSet.rowCount === 0) {
  89. callback(false, 'Error: Target file not found in database');
  90. resultSet.close();
  91. return;
  92. }
  93. resultSet.close();
  94. // Step 3: 构建更新条件与数据
  95. const updatePredicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
  96. updatePredicates.equalTo('filePath', filePath);
  97. const valueBucket: relationalStore.ValuesBucket = {
  98. pixelMapPath: newPixelMapPath
  99. };
  100. // Step 4: 执行原子化更新操作
  101. this.accountTable.updateData(updatePredicates, valueBucket, (success: boolean) => {
  102. callback(success, success ? null : 'Database update operation failed');
  103. });
  104. });
  105. }
  106. updateData(item: VideoItem, callback: Function) {
  107. const valueBucket: relationalStore.ValuesBucket = generateBucket(item);
  108. let predicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
  109. predicates.equalTo('id', item.id);
  110. this.accountTable.updateData(predicates, valueBucket, callback);
  111. }
  112. //编辑歌曲的信息更新数据库
  113. public updateMediaInfo(filePath: string, title: string, artist: string, album: string, callback: Function) {
  114. if (!callback || typeof callback !== 'function') {
  115. Logger.info(RdbUtils.RDB_TAG, 'updateMediaInfo() has no valid callback!');
  116. return;
  117. }
  118. if (!this.accountTable) {
  119. Logger.error(RdbUtils.RDB_TAG, 'RdbStore is not initialized.');
  120. callback(false);
  121. return;
  122. }
  123. // Step 1: Create a predicate to find the record by filePath
  124. const predicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
  125. predicates.equalTo('filePath', filePath);
  126. // Step 2: Query the database to check if the record exists
  127. this.accountTable.query(predicates, (resultSet: relationalStore.ResultSet) => {
  128. if (resultSet.rowCount === 0) {
  129. Logger.info(RdbUtils.RDB_TAG, `No record found with filePath ${filePath}.`);
  130. callback(false);
  131. resultSet.close();
  132. return;
  133. }
  134. // Step 3: Prepare the values to update
  135. const valuesToUpdate: relationalStore.ValuesBucket = {};
  136. if (title !== '') {
  137. valuesToUpdate.name = title;
  138. }
  139. if (artist !== '') {
  140. valuesToUpdate.artist = artist;
  141. }
  142. if (album !== '') {
  143. valuesToUpdate.album = album;
  144. }
  145. resultSet.close();
  146. // Step 4: Update the record if there are values to update
  147. if (Object.keys(valuesToUpdate).length > 0) {
  148. this.accountTable.updateData(predicates, valuesToUpdate, (success: boolean) => {
  149. callback(success, success ? null : 'Database update operation failed');
  150. });
  151. } else {
  152. Logger.info(RdbUtils.RDB_TAG, 'No fields to update.');
  153. callback(false);
  154. }
  155. });
  156. }
  157. //更新重命名数据操作
  158. public updateRename(newName: string, oldPath: string, newPath: string, callback: Function) {
  159. // Step 1: 查询原始记录
  160. const queryPredicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
  161. queryPredicates.equalTo('filePath', oldPath);
  162. this.accountTable.query(queryPredicates, (resultSet: relationalStore.ResultSet) => {
  163. if (resultSet.rowCount === 0) {
  164. callback(false, 'Error: File not found');
  165. return;
  166. }
  167. resultSet.goToFirstRow();
  168. // Step 3: 构建更新数据
  169. const currentName = resultSet.getString(resultSet.getColumnIndex('name'));
  170. const currentFileName = resultSet.getString(resultSet.getColumnIndex('fileName'));
  171. let obj: relationalStore.ValuesBucket = {};
  172. obj.id = newPath
  173. obj.filePath = newPath;
  174. if (currentName === currentFileName) {
  175. obj.name = newName;
  176. obj.fileName = newName;
  177. } else {
  178. obj.fileName = newName;
  179. }
  180. obj.mtype = resultSet.getDouble(resultSet.getColumnIndex('mtype'));
  181. obj.videoSize = resultSet.getDouble(resultSet.getColumnIndex('videoSize'));
  182. obj.cTime = resultSet.getString(resultSet.getColumnIndex('cTime'));
  183. obj.parentPath = resultSet.getString(resultSet.getColumnIndex('parentPath'));
  184. // obj.pixelMapToString = resultSet.getString(resultSet.getColumnIndex('pixelMapToString'));
  185. obj.artist = resultSet.getString(resultSet.getColumnIndex('artist'));
  186. obj.album = resultSet.getString(resultSet.getColumnIndex('album'));
  187. obj.isFav = resultSet.getDouble(resultSet.getColumnIndex('isFav'));
  188. obj.pixelMapPath = resultSet.getString(resultSet.getColumnIndex('pixelMapPath'));
  189. obj.duration = resultSet.getString(resultSet.getColumnIndex('duration'));
  190. obj.mimeType = resultSet.getString(resultSet.getColumnIndex('mimeType'));
  191. obj.trackCount = resultSet.getString(resultSet.getColumnIndex('trackCount'));
  192. obj.sampleRate = resultSet.getString(resultSet.getColumnIndex('sampleRate'));
  193. obj.lastPlayedStr = resultSet.getString(resultSet.getColumnIndex('lastPlayedStr'));
  194. obj.playCount = resultSet.getDouble(resultSet.getColumnIndex('playCount'));
  195. obj.lyricContent = resultSet.getString(resultSet.getColumnIndex('lyricContent'));
  196. const valueBucket: relationalStore.ValuesBucket = obj
  197. // Step 4: 执行更新
  198. const updatePredicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
  199. updatePredicates.equalTo('filePath', oldPath);
  200. this.accountTable.updateData(updatePredicates, valueBucket, (success: boolean) => {
  201. callback(success, success ? null : 'Update failed');
  202. });
  203. resultSet.close()
  204. });
  205. }
  206. // 根据isFav查询数据
  207. public queryByisFav(isFav: number, callback: (result: VideoItem[]) => void) {
  208. const predicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
  209. predicates.equalTo('isFav', isFav);
  210. this.accountTable.query(predicates, (resultSet: relationalStore.ResultSet) => {
  211. const result = this.parseResultSetToVideoItems(resultSet);
  212. callback(result);
  213. });
  214. }
  215. // 根据filePath更新isFav的值
  216. public updateIsFavByFilePath(filePath: string, isFav: number, callback: (success: boolean, error?: string) => void) {
  217. const predicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
  218. predicates.equalTo('filePath', filePath);
  219. this.accountTable.query(predicates, (resultSet: relationalStore.ResultSet) => {
  220. if (resultSet.rowCount === 0) {
  221. callback(false, 'Error: File not found');
  222. resultSet.close();
  223. return;
  224. }
  225. resultSet.close();
  226. const valueBucket: relationalStore.ValuesBucket = { isFav: isFav };
  227. this.accountTable.updateData(predicates, valueBucket, (success: boolean) => {
  228. callback(success, success ? '' : 'Update failed');
  229. });
  230. });
  231. }
  232. // 查询全部,或者某个id(查询的字段,回调,是否查询全部)
  233. query(id: number, callback: Function, isAll: boolean = true) {
  234. let predicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
  235. if (!isAll) {
  236. predicates.equalTo('id', id);
  237. }
  238. this.accountTable.query(predicates, (resultSet: relationalStore.ResultSet) => {
  239. let count: number = resultSet.rowCount;
  240. if (count === 0 || typeof count === 'string') {
  241. console.log(`${RdbUtils.RDB_TAG}` + 'Query no results!');
  242. callback([]);
  243. } else {
  244. const result = this.parseResultSetToVideoItems(resultSet);
  245. callback(result);
  246. }
  247. });
  248. }
  249. // 新增方法:根据parentPath查询数据
  250. public queryByParentPath(path: string, callback: (result: VideoItem[]) => void) {
  251. try {
  252. const predicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
  253. predicates.equalTo('parentPath', path);
  254. // 2. 执行查询并处理结果
  255. this.accountTable.query(predicates, (resultSet: relationalStore.ResultSet) => {
  256. // 3. 复用已有的解析逻辑
  257. const result = this.parseResultSetToVideoItems(resultSet);
  258. callback(result);
  259. });
  260. }catch (err) {
  261. Logger.error(` onecold testtag queryByParentPath: ${err.code} - ${err.message}`);
  262. }
  263. // 1. 构建查询条件
  264. }
  265. // 查询所有艺术家及其歌曲(返回Map结构:artist -> VideoItem[])
  266. public queryArtistsWithSongs(callback: (result: Map<string, VideoItem[]>) => void) {
  267. // 1. 查询去重的艺术家列表(非空)
  268. const artistPredicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
  269. artistPredicates.isNotNull('artist').distinct();
  270. this.accountTable.query(artistPredicates, (resultSet: relationalStore.ResultSet) => {
  271. const artists: string[] = this.parseDistinctColumn(resultSet, 'artist');
  272. // 2. 遍历每个艺术家,查询其歌曲
  273. const resultMap = new Map<string, VideoItem[]>();
  274. let processedCount = 0;
  275. if (artists.length === 0) {
  276. callback(resultMap);
  277. return;
  278. }
  279. artists.forEach(artist => {
  280. const songPredicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
  281. songPredicates.equalTo('artist', artist);
  282. this.accountTable.query(songPredicates, (songResultSet: relationalStore.ResultSet) => {
  283. const songs = this.parseResultSetToVideoItems(songResultSet);
  284. resultMap.set(artist, songs);
  285. processedCount++;
  286. // 3. 全部查询完成后回调
  287. if (processedCount === artists.length) {
  288. callback(resultMap);
  289. }
  290. });
  291. });
  292. });
  293. }
  294. // 查询所有专辑及其歌曲(返回Map结构:album -> VideoItem[])
  295. public queryAlbumsWithSongs(callback: (result: Map<string, VideoItem[]>) => void) {
  296. // 1. 查询去重的专辑列表(非空)
  297. const albumPredicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
  298. albumPredicates.isNotNull('album').distinct();
  299. this.accountTable.query(albumPredicates, (resultSet: relationalStore.ResultSet) => {
  300. const albums: string[] = this.parseDistinctColumn(resultSet, 'album');
  301. // 2. 遍历每个专辑,查询其歌曲
  302. const resultMap = new Map<string, VideoItem[]>();
  303. let processedCount = 0;
  304. if (albums.length === 0) {
  305. callback(resultMap);
  306. return;
  307. }
  308. albums.forEach(album => {
  309. const songPredicates = new relationalStore.RdbPredicates(RdbUtils.MEDIA_TABLE.tableName);
  310. songPredicates.equalTo('album', album);
  311. this.accountTable.query(songPredicates, (songResultSet: relationalStore.ResultSet) => {
  312. const songs = this.parseResultSetToVideoItems(songResultSet);
  313. resultMap.set(album, songs);
  314. processedCount++;
  315. // 3. 全部查询完成后回调
  316. if (processedCount === albums.length) {
  317. callback(resultMap);
  318. }
  319. });
  320. });
  321. });
  322. }
  323. // 解析去重列数据(如artist/album)
  324. private parseDistinctColumn(resultSet: relationalStore.ResultSet, columnName: string): string[] {
  325. const uniqueValues = new Set<string>(); // 使用Set特性自动去重
  326. if (resultSet.rowCount > 0) {
  327. resultSet.goToFirstRow();
  328. for (let i = 0; i < resultSet.rowCount; i++) {
  329. const value = resultSet.getString(resultSet.getColumnIndex(columnName))?.trim(); // 处理空格
  330. if (value) { // 过滤空值
  331. uniqueValues.add(value);
  332. }
  333. if (i < resultSet.rowCount - 1) { // 避免最后一行越界
  334. resultSet.goToNextRow();
  335. }
  336. }
  337. }
  338. resultSet.close();
  339. return Array.from(uniqueValues); // Set转数组
  340. }
  341. // 将ResultSet解析为VideoItem数组(复用原有逻辑)
  342. private parseResultSetToVideoItems(resultSet: relationalStore.ResultSet): VideoItem[] {
  343. const items: VideoItem[] = [];
  344. try {
  345. // 检查结果集是否有效
  346. if (resultSet && resultSet.rowCount > 0) {
  347. while (resultSet.goToNextRow()) {
  348. const item = this.buildVideoItem(resultSet);
  349. items.push(item);
  350. }
  351. }
  352. } catch (err) {
  353. Logger.error(`解析结果集出错: ${err.message}`);
  354. } finally {
  355. // 确保结果集被关闭
  356. if (resultSet) {
  357. resultSet.close();
  358. }
  359. }
  360. return items;
  361. }
  362. private buildVideoItem(rs: relationalStore.ResultSet): VideoItem {
  363. // 添加空值保护
  364. const safeGet = (col: string) => {
  365. const index = rs.getColumnIndex(col);
  366. return index >= 0 ? rs.getString(index) || '' : '';
  367. };
  368. const safeGetNumber = (col: string) => {
  369. const index = rs.getColumnIndex(col);
  370. return index >= 0 ? rs.getDouble(index) || 0 : 0;
  371. };
  372. let item = new VideoItem(
  373. safeGet(DB_COLUMNS.NAME),
  374. safeGet(DB_COLUMNS.ID),
  375. safeGet(DB_COLUMNS.FILE_PATH),
  376. safeGetNumber(DB_COLUMNS.TYPE),
  377. safeGetNumber(DB_COLUMNS.VIDEO_SIZE),
  378. safeGet(DB_COLUMNS.C_TIME),
  379. undefined,
  380. safeGet(DB_COLUMNS.SIZE),
  381. safeGet(DB_COLUMNS.PIXEL_MAP_PATH),
  382. safeGet(DB_COLUMNS.ARTIST),
  383. safeGet(DB_COLUMNS.ALBUM),
  384. safeGet(DB_COLUMNS.FILE_NAME)
  385. );
  386. // 设置额外属性,添加安全检查
  387. item.isFav = safeGetNumber(DB_COLUMNS.IS_FAV);
  388. item.duration = safeGet(DB_COLUMNS.DURATION);
  389. item.mimeType = safeGet(DB_COLUMNS.MIME_TYPE);
  390. item.trackCount = safeGet(DB_COLUMNS.TRACK_COUNT);
  391. item.sampleRate = safeGet(DB_COLUMNS.SAMPLE_RATE);
  392. item.lastPlayedStr = safeGet(DB_COLUMNS.LAST_PLAYED_STR);
  393. item.playCount = safeGetNumber(DB_COLUMNS.PLAY_COUNT);
  394. item.lyricContent = safeGet(DB_COLUMNS.LYRIC_CONTENT);
  395. return item;
  396. }
  397. }
  398. function generateBucket(item: VideoItem): relationalStore.ValuesBucket {
  399. let obj: relationalStore.ValuesBucket = {};
  400. obj.id = item.id
  401. obj.name = item.name;
  402. obj.filePath = item.filePath;
  403. obj.mtype = item.type;
  404. obj.videoSize = item.videoSize;
  405. obj.cTime = item.cTime;
  406. obj.parentPath = item.parentPath;
  407. obj.isFav = item.isFav;
  408. // if(item.pixelMapToString){
  409. // obj.pixelMapToString = item.pixelMapToString;
  410. // }
  411. if(item.artist){
  412. obj.artist = item.artist;
  413. }
  414. if(item.album){
  415. obj.album = item.album;
  416. }
  417. if(item.fileName){
  418. obj.fileName = item.fileName;
  419. }
  420. if(item.size){
  421. obj.size = item.size;
  422. }
  423. if(item.pixelMapPath){
  424. obj.pixelMapPath = item.pixelMapPath;
  425. }
  426. if(item.duration){
  427. obj.duration = item.duration;
  428. }
  429. if(item.mimeType){
  430. obj.mimeType = item.mimeType;
  431. }
  432. if(item.trackCount){
  433. obj.trackCount = item.trackCount;
  434. }
  435. if(item.sampleRate){
  436. obj.sampleRate = item.sampleRate;
  437. }
  438. if(item.lastPlayedStr){
  439. obj.lastPlayedStr = item.lastPlayedStr;
  440. }
  441. if(item.playCount){
  442. obj.playCount = item.playCount;
  443. }
  444. if(item.lyricContent){
  445. obj.lyricContent = item.lyricContent;
  446. }
  447. return obj;
  448. }