| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294 |
- import { BusinessError, pasteboard } from '@kit.BasicServicesKit';
- import {
- AppUtil,
- ArrayUtil,
- Base64Util,
- DateUtil, FileUtil, ImageUtil, LogUtil,
- MD5,
- PreferencesUtil,
- RandomUtil, StrUtil, ToastUtil } from '@pura/harmony-utils';
- import { media } from '@kit.MediaKit';
- import fs from '@ohos.file.fs';
- import { image } from '@kit.ImageKit';
- import fileIo from '@ohos.file.fs';
- import { VideoItem } from '../../viewmodel/VideoItem';
- import { photoAccessHelper } from '@kit.MediaLibraryKit';
- import { dataSharePredicates, uniformTypeDescriptor } from '@kit.ArkData';
- import { systemShare } from '@kit.ShareKit';
- import { fileUri } from '@kit.CoreFileKit';
- import { common, UIAbility, Want } from '@kit.AbilityKit';
- import { CommonConstants } from '../constants/CommonConstants';
- import { window } from '@kit.ArkUI';
- import { bundleManager } from '@kit.AbilityKit'
- import { VipPage } from '../../pages/VipPage';
- import NetAxiosUtil from './NetAxiosUtil';
- // import userFileManager from '@ohos.filemanagement.userFileManager';
- export class Utility {
- private constructor() {}
- static isOpenTime():boolean{
- const currentDate = new Date();
- const targetDate = new Date(CommonConstants.OPEN_DATE);
- if (currentDate > targetDate) {
- return true
- }
- return false
- }
- //是否赞助
- static isNoble():boolean{
- if(!Utility.isOpenTime())//提交审核的审核,刚刚开始可以全部是赞助用户。
- return true
- return PreferencesUtil.getBooleanSync('isNoble',false)
- }
- //判断用户安装app是否超过2天,超过2天(2800分钟)才展示广告 显示广告 24*60=1440 1440*2=2800
- static isPassInstallTime(day:number):boolean{
- //获取当前时间
- let currentTime = new Date().getTime();
- // 尝试从存储中获取安装时间
- let installTime = getInstallTime();
- if (installTime===0||installTime === null|| installTime===undefined) {
- // 如果没有存储安装时间,则存储当前时间为安装时间
- setInstallTime(currentTime);
- return false
- } else {
- // 计算时间差(以分钟为单位)
- const timeDifference = (currentTime - installTime) / (1000 * 60);
- LogUtil.debug("onecold timeDifference=" + timeDifference)
- // 如果超过5分钟,显示广告 24*60=1440 1440*2=2800
- if (timeDifference > 24*60*day) {
- return true
- }else{
- return false
- }
- }
- }
- static optimizedFormat(speed: number): string {
- if (speed) {
- const str = speed.toFixed(2);
- let end = str.length;
- while (end > 0 && (str[end - 1] === '0' || str[end - 1] === '.')) {
- end--;
- if (str[end] === '.') {
- break;
- }
- }
- return str.slice(0, end || 1) + 'x';
- } else {
- return '1x'
- }
- }
- static isHaoOpenTime():boolean{
- const currentDate = new Date();
- const targetDate = new Date('2025-04-20');
- if (currentDate < targetDate) {
- return true
- }
- return false
- }
- static setNoble(expireDate:string){
- let isNoble = false
- if(StrUtil.isNotEmpty(expireDate)){
- if(expireDate===VipPage.FOEVEER_DATE){
- isNoble = true
- }else{
- const currentDate = new Date();
- const targetDate = DateUtil.getFormatDate(expireDate)
- if (currentDate > targetDate) {
- isNoble = false
- }else{
- isNoble = true
- }
- }
- }
- PreferencesUtil.putSync('isNoble',isNoble)
- }
- static addDays(date: Date, days: number): Date {
- const result = new Date(date);
- result.setDate(result.getDate() + days);
- return result;
- }
- static convertToKHz(sampleRateHz: string|undefined): string {
- if(StrUtil.isEmpty(sampleRateHz) || sampleRateHz === undefined || sampleRateHz === "0") {
- return '未知';
- }
- try {
- const sampleRateNum = Number(sampleRateHz);
- if (isNaN(sampleRateNum) || sampleRateNum <= 0) {
- return '未知';
- }
- const sampleRateKHz = sampleRateNum / 1000;
- return `${sampleRateKHz.toFixed(1)} KHz`;
- } catch (err) {
- console.error(`转换采样率出错: ${err}`);
- return '未知';
- }
- }
- /**
- * 格式化媒体格式类型显示
- * @param mimeType 媒体格式类型字符串
- * @return 格式化后的显示字符串
- */
- static formatMimeType(mimeType: string|undefined): string {
- if(StrUtil.isEmpty(mimeType) || mimeType === undefined) {
- return '未知';
- }
-
- // 从MIME类型中提取格式部分,例如 "audio/mp3" -> "MP3"
- try {
- const parts = mimeType.split('/');
- if (parts.length > 1) {
- return parts[1].toUpperCase();
- } else {
- return mimeType.toUpperCase();
- }
- } catch (err) {
- console.error(`格式化媒体类型出错: ${err}`);
- return '未知';
- }
- }
- /**
- * 格式化媒体格式类型显示
- * @param mimeType 媒体格式类型字符串
- * @return 格式化后的显示字符串
- */
- static formatMimeType(mimeType: string | undefined): string {
- if (StrUtil.isEmpty(mimeType) || mimeType === undefined) {
- return 'unknown';
- }
- // 从MIME类型中提取格式部分,例如 "audio/mp3" -> "MP3"
- try {
- const parts = mimeType.split('/');
- if (parts.length > 1) {
- return parts[1].toUpperCase();
- } else {
- return mimeType.toUpperCase();
- }
- } catch (err) {
- console.error(`格式化媒体类型出错: ${err}`);
- return 'unknown';
- }
- }
- //根据字节获取大小
- static formatFileSize(bytes:number) {
- const units = ['Bytes', 'Kbps', 'Mbps'];
- let size = bytes;
- let unitIndex = 0;
- while (size >= 1024 && unitIndex < units.length - 1) {
- size /= 1024;
- unitIndex++;
- }
- if(size > 1024&&unitIndex==2){
- size = size*0.1
- }
- if(size > 1024&&unitIndex==2){
- size = size*0.1
- }
- if(size > 480&&unitIndex==2){
- size = size*0.5
- }
- // 保留两位小数, 四舍五入
- size = Math.round(size * 10) / 10;
- return size + units[unitIndex]
- }
- //根据字节获取大小无单位
- static formatFileSizeWithout(bytes:number) {
- const units = ['Bytes', 'Kbps', 'Mbps'];
- let size = bytes;
- let unitIndex = 0;
- while (size >= 1024 && unitIndex < units.length - 1) {
- size /= 1024;
- unitIndex++;
- }
- if(size > 1024&&unitIndex==2){
- size = size*0.1
- }
- if(size > 1024&&unitIndex==2){
- size = size*0.1
- }
- if(size > 480&&unitIndex==2){
- size = size*0.5
- }
- // 保留两位小数, 四舍五入
- size = Math.round(size * 10) / 10;
- return size
- }
- static copyText(text:string):boolean{
- const pasteboardData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN,text)
- const systemPasteboard = pasteboard.getSystemPasteboard()
- systemPasteboard.setData(pasteboardData)
- systemPasteboard.getData().then((data)=>{
- return data
- })
- return false
- }
- static getDbm(rssi:number):number{
- return Math.round((rssi / 2) + 100)
- }
- //根据数字形式的IP地址获取字符串形式的IP地址
- static getIpAddrFromNum(ipNum: number): string {
- return (ipNum >>> 24) + '.' + (ipNum >> 16 & 0xFF) + '.' + (ipNum >> 8 & 0xFF) + '.' + (ipNum & 0xFF);
- }
- static resolveIP(ip:number) {
- let address: string = ip.toString()
- if (address === '0') {
- return '00:00:000:000'
- }
- address.substring(0, 2)
- return `${address.substring(0, 2)}:${address.substring(2, 4)}:${address.substring(4, 7)}:${address.substring(7, 10)}`
- }
- static isFreeTime():boolean{
- if(DateUtil.isWeekend()){
- return true
- }
- let str = DateUtil.getFormatDateStr(new Date(), 'HH')
- let a = Number(str);
- if(isNaN(a))
- return false
- // ToastUtil.showToast('a='+a)
- if (a >= 7 && a <13) {//白天
- return false;
- }
- if (a >= 13 && a <20) {//白天
- return false;
- }
- if (a >= 0 && a < 7) {//凌晨
- return true;
- }
- if (a >= 20 && a <= 24) {//晚上
- return true;
- }
- return false
- }
- //判断是否是音乐文件
- static isMusicByExtension(filename:string) {
- const extensions = CommonConstants.REAL_MUSIC_FORMAT
- const lastIndex = filename.lastIndexOf('.');
- if (lastIndex!== -1) {
- const fileExtension = filename.slice(lastIndex).toLowerCase();
- return extensions.includes(fileExtension);
- }
- return false;
- }
- //判断是否是媒体文件 音乐和视频都可以
- static isMeidaByExtension(filename:string) {
- const extensions = CommonConstants.MEDIA_FORMAT
- const lastIndex = filename.lastIndexOf('.');
- if (lastIndex!== -1) {
- const fileExtension = filename.slice(lastIndex).toLowerCase();
- return extensions.includes(fileExtension);
- }
- return false;
- }
- //判断是否是视频文件
- static isVideoByExtension(filename:string) {
- const extensions = CommonConstants.VIDEO_FORMAT
- const lastIndex = filename.lastIndexOf('.');
- if (lastIndex!== -1) {
- const fileExtension = filename.slice(lastIndex).toLowerCase();
- return extensions.includes(fileExtension);
- }
- return false;
- }
- // 获取缩略图
- static async getFetchFrameByTime(filePath: string) {
- if(Utility.isMusicByExtension(filePath)){
- return undefined
- }
- let pixelMap:image.PixelMap|undefined =undefined;
- try{
- // 创建AVImageGenerator对象
- let avImageGenerator: media.AVImageGenerator = await media.createAVImageGenerator()
- let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
- let avFileDescriptor: media.AVFileDescriptor = { fd: file.fd };
- avImageGenerator.fdSrc = avFileDescriptor;
- // 初始化入参
- let timeUs = 0
- let queryOption = media.AVImageQueryOptions.AV_IMAGE_QUERY_NEXT_SYNC
- let param: media.PixelMapParams = {
- width : 300,
- height : 400,
- }
- // 获取缩略图(promise模式)
- pixelMap = await avImageGenerator.fetchFrameByTime(timeUs, queryOption, param)
- // 释放资源(promise模式)
- avImageGenerator.release()
- console.info(`release success.`)
- fs.closeSync(file);
- }catch (error) {
- console.error('uriGetAssets failed with err: ' + JSON.stringify(error));
- }
- return pixelMap
- }
- // 获取fd文件路径
- static async getFdDir(path:string){
- let fdPath = 'fd://';
- let file = await fileIo.open(path)
- fdPath = fdPath + '' + file.fd;
- return fdPath
- }
- // 根据uri获取文件名称
- static getMediaNameByUri(myUri: string) {
- let myFileName = (myUri.split('/').pop()) as string;
- return decodeURIComponent(myFileName)
- }
- static msToStandardTime(ms:string):string{
- let date = new Date(ms);
- let hours = date.getHours();
- let minutes = date.getMinutes();
- let seconds = date.getSeconds();
- return hours + ':' + minutes + ':' + seconds;
- }
- //获取资源的属性值
- static async uriGetAssets(context:Context,uri:string,type:number): Promise<VideoItem> {
- let isFromFileMan:boolean = false
- if(uri.startsWith('file://media')){//图库的视频
- isFromFileMan = false
- }else{//从文件管理器
- isFromFileMan = true
- }
- if(isFromFileMan){
- return await Utility.uriGetAssetsFromFile(context,uri,type);
- }
- try {
- let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
- let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
- // 配置查询条件,使用PhotoViewPicker选择图片返回的uri进行查询
- predicates.equalTo('uri', uri);
- let fetchOption: photoAccessHelper.FetchOptions = {
- fetchColumns: [photoAccessHelper.PhotoKeys.WIDTH, photoAccessHelper.PhotoKeys.HEIGHT,
- photoAccessHelper.PhotoKeys.TITLE, photoAccessHelper.PhotoKeys.SIZE, photoAccessHelper.PhotoKeys.DURATION],
- predicates: predicates
- };
- let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> =
- await phAccessHelper.getAssets(fetchOption);
- // 得到uri对应的PhotoAsset对象,读取文件的部分信息
- const asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
- let fd = await Utility.getFdDir(uri)
- let videoSize = asset.get(photoAccessHelper.PhotoKeys.SIZE).toString()
- let videoTime = asset.get(photoAccessHelper.PhotoKeys.DATE_ADDED_MS).toString()
- let fileSize = Utility.formatFSize(Number(videoSize))
- let cTime = Utility.getFormatDateStr(videoTime,'yyyy-MM-dd HH:mm')
- // let modifyDate = asset.get(photoAccessHelper.PhotoKeys.DATE_MODIFIED_MS).toString()
- let item:VideoItem = new VideoItem( asset.displayName, fd,uri,type,Number(videoSize),cTime,
- await Utility.getFetchFrameByTime(uri),fileSize)
- console.info('asset displayName: ', asset.displayName);
- console.info('asset uri: ', asset.uri);
- console.info('asset photoType: ', asset.photoType);
- console.info('asset width: ', asset.get(photoAccessHelper.PhotoKeys.WIDTH));
- console.info('asset height: ', asset.get(photoAccessHelper.PhotoKeys.HEIGHT));
- console.info('asset SIZE: ' + asset.get(photoAccessHelper.PhotoKeys.SIZE));
- console.info('asset DURATION: ' + asset.get(photoAccessHelper.PhotoKeys.DURATION));
- // 获取缩略图
- // asset.getThumbnail((err, pixelMap) => {
- // if (err == undefined) {
- // console.info('getThumbnail successful ' + JSON.stringify(pixelMap));
- // } else {
- // console.error('getThumbnail fail', err);
- // }
- // });
- return item
- } catch (error) {
- console.error('uriGetAssets failed with err: ' + JSON.stringify(error));
- return new VideoItem('','','',0,0,'')
- }
- }
- static getTimestampFromDateStr(dateStr: string, format: string = 'yyyy-MM-dd HH:mm'): number {
- // 定义正则表达式以匹配日期字符串中的各部分
- const regex = format
- .replace('yyyy', '(\\d{4})')
- .replace('MM', '(\\d{2})')
- .replace('dd', '(\\d{2})')
- .replace('HH', '(\\d{2})')
- .replace('mm', '(\\d{2})');
- const match = new RegExp(regex).exec(dateStr);
- if (!match) {
- throw new Error('Invalid date string or format');
- }
- // 解析匹配结果
- const year = Number(match[1]);
- const month = Number(match[2]);
- const day = Number(match[3]);
- const hours = Number(match[4]);
- const minutes = Number(match[5]);
- // 创建 Date 对象
- const dateObj = new Date(year, month - 1, day, hours, minutes);
- // 返回时间戳(以秒为单位)
- return Math.floor(dateObj.getTime() / 1000);
- }
- static getFormatDateStr(date: number | string | Date, format: string = 'yyyy-MM-dd HH:mm:ss'): string {
- // 将输入转换为 Date 对象
- let dateObj: Date;
- if (typeof date === 'number') {
- // 如果是十位时间戳,转换为毫秒数
- dateObj = new Date(date.toString().length === 10 ? date * 1000 : date);
- } else if (typeof date === 'string') {
- // 如果是字符串,尝试解析为 Date 对象
- dateObj = new Date(date);
- } else {
- // 如果是 Date 对象,直接使用
- dateObj = date;
- }
- // 定义替换规则
- const replacements = new Map<string, string>([
- ['yyyy', String(dateObj.getFullYear())],
- ['MM', String(dateObj.getMonth() + 1).padStart(2, '0')],
- ['dd', String(dateObj.getDate()).padStart(2, '0')],
- ['HH', String(dateObj.getHours()).padStart(2, '0')],
- ['mm', String(dateObj.getMinutes()).padStart(2, '0')],
- ['ss', String(dateObj.getSeconds()).padStart(2, '0')]
- ]);
- // 替换格式字符串中的占位符
- replacements.forEach((value, key) => {
- format = format.replace(new RegExp(key, 'g'), value);
- });
- return format;
- }
- //获取从文件管理器获得的视频资源的属性值
- static async uriGetAssetsFromFile(context:Context,uri:string,type:number,isLoadPixelMap?:boolean): Promise<VideoItem> {
- let item:VideoItem = new VideoItem('',uri,uri,type,0,'')
- try {
- console.info('asset file.uri: ', uri);
- let file = fs.openSync(uri, fs.OpenMode.READ_ONLY | fs.OpenMode.CREATE)
- console.info("file.fd " + file.fd);
- let fdfd = 'fd://' + file.fd
- //3、通过fs.stat方法获取stat对象
- console.info('asset file.name: ', file.name);
- console.info('asset file.uri: ', uri);
- console.info('asset file.fd: ', file.fd);
- console.info('asset file.path: ', file.path);
- item = new VideoItem(file.name,uri,uri,type,0,'')
- await fs.stat(file.fd).then(async (stat: fs.Stat) => {
- console.info("get file info succeed, the size of file is " + stat.size);
- let videoSize = stat.size
- // let videoTime = stat.ctime
- let fileSize = Utility.formatFSize(videoSize)
- let cTime = Utility.getFormatDateStr(stat.mtime,'yyyy-MM-dd HH:mm')
- // console.info('asset stat.ino: ', stat.ino);
- // console.info('asset stat.mode: ', stat.mode);
- // console.info('asset stat.uid: ', stat.uid);
- // console.info('asset stat.ino: ', stat.gid);
- // console.info('asset stat.size: ', stat.size);
- console.info('asset stat.ctime: ', stat.ctime);
- // console.info('asset stat.mtime: ', stat.mtime);
- // console.info('asset stat.duration: ', duration);
- let pixelMap:image.PixelMap|undefined = undefined
- if(isLoadPixelMap){
- //获取缩略图
- if(Utility.isVideoByExtension(uri)){
- pixelMap = await Utility.getFetchFrameByTime(uri)
- }else{
- pixelMap = await Utility.getFetchMetadataFromFdSrcByPromise(uri)
- }
- }
- item = new VideoItem( file.name,uri ,uri,type,videoSize,cTime,pixelMap,fileSize,
- await ImageUtil.pixelMapToBase64Str(pixelMap))
- })
- } catch (error) {
- console.error('uriGetAssetsFromFile failed with err: ' + JSON.stringify(error));
- }
- return item
- }
- static async getFilePixelMapBig(uri:string){
- let pixelMap:image.PixelMap|undefined = undefined
- if(Utility.isMusicByExtension(uri)){
- pixelMap = await Utility.getFetchMetadataFromFdSrcByPromise(uri)
- }else{
- pixelMap = await Utility.getFetchFrameByTime(uri)
- }
- return ImageUtil.pixelMapToBase64StrBig(pixelMap)
- }
- static async getFilePixelMap(uri:string){
- let pixelMap:image.PixelMap|undefined = undefined
- if(Utility.isMusicByExtension(uri)){
- pixelMap = await Utility.getFetchMetadataFromFdSrcByPromise(uri)
- }else{
- pixelMap = await Utility.getFetchFrameByTime(uri)
- }
- return ImageUtil.pixelMapToBase64Str(pixelMap)
- }
- //根据filePathe获取对应的播放Index
- static getIndexFromList(localList:Array<VideoItem>,filePath:string){
- let list: Array<string> = [];
- for(let i=0;i<localList.length;i++){
- if(localList[i].filePath === filePath){
- return i
- }
- }
- return 0
- }
- // 在以下demo中,使用资源管理接口获取打包在HAP内的媒体资源文件,通过设置fdSrc属性,获取音频元数据并打印,
- // 获取音频专辑封面并通过Image控件显示在屏幕上。该demo以Promise形式进行异步接口调用
- static async getFetchMetadataFromFdSrcByPromise(uri: string): Promise<image.PixelMap | undefined> {
- let cover: image.PixelMap | undefined = undefined;
- if (canIUse("SystemCapability.Multimedia.Media.AVMetadataExtractor")) {
- try {
- // 创建AVMetadataExtractor对象
- const avMetadataExtractor: media.AVMetadataExtractor = await media.createAVMetadataExtractor();
- // 设置fdSrc
- const fd = await fs.openSync(uri, fs.OpenMode.READ_ONLY);
- avMetadataExtractor.fdSrc = fd;
- // 获取元数据(promise模式)
- const metadata = await avMetadataExtractor.fetchMetadata();
- metadata.author
- console.info(`get meta data, hasAudio: ${metadata.hasAudio}`);
- // 获取专辑封面(promise模式)
- cover = await avMetadataExtractor.fetchAlbumCover();
- // 释放资源(promise模式)
- await avMetadataExtractor.release();
- console.info('release success.');
- } catch (error) {
- console.error('Error during metadata extraction:', error);
- }
- } else {
- console.warn('AVMetadataExtractor capability is not supported.');
- }
- return cover;
- }
- static formatTimestamp(timestamp: number): string {
- // 将时间戳转换为 Date 对象
- const date = new Date(timestamp);
- // 获取各个部分
- const year = date.getFullYear();
- const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需要加1
- const day = String(date.getDate()).padStart(2, '0');
- const hours = String(date.getHours()).padStart(2, '0');
- const minutes = String(date.getMinutes()).padStart(2, '0');
- const seconds = String(date.getSeconds()).padStart(2, '0');
- // 拼接成所需的格式
- return `${year}-${month}-${day} ${hours}:${minutes}`;
- }
- //获取音乐资源的属性值,
- static async uriGetMusicAssetsFromFile(context:Context,uri:string,type:number,isLoadPixelMap?:boolean): Promise<VideoItem> {
- let item:VideoItem = new VideoItem('',uri,uri,type,0,'')
- try {
- console.info('asset file.uri: ', uri);
- let file = fs.openSync(uri, fs.OpenMode.READ_ONLY | fs.OpenMode.CREATE)
- console.info("file.fd " + file.fd);
- let fdfd = 'fd://' + file.fd
- //3、通过fs.stat方法获取stat对象
- console.info('asset file.name: ', file.name);
- console.info('asset file.uri: ', uri);
- console.info('asset file.fd: ', file.fd);
- console.info('asset file.path: ', file.path);
- item = new VideoItem(file.name,uri,uri,type,0,'')
- await fs.stat(file.fd).then(async (stat: fs.Stat) => {
- console.info("get file info succeed, the size of file is " + stat.size);
- let videoSize = stat.size
- // let videoTime = stat.ctime
- let fileSize = Utility.formatFSize(videoSize)
- //按照添加时间
- let addTime = Utility.getFormatDateStr(new Date(),'yyyy-MM-dd HH:mm');
- // console.info('onecold asset addTime: ', addTime);
- // let cTime = Utility.getFormatDateStr(stat.mtime,'yyyy-MM-dd HH:mm')
- // console.info('asset stat.ctime: ', stat.ctime);
- let musicName:string | undefined = file.name
- let artist:string | undefined = ''
- let album:string | undefined = ''
- let pixelMap:image.PixelMap|undefined|null = undefined
- let imagePath = ''
- let duration:string | undefined = ''
- let mimeType:string | undefined = ''
- let trackCount:string | undefined = ''//轨道数量
- let sampleRate:string | undefined = ''//音频的采样率单位为Hz
- if (canIUse("SystemCapability.Multimedia.Media.AVMetadataExtractor")) {
- try {
- // 创建AVMetadataExtractor对象
- const avMetadataExtractor: media.AVMetadataExtractor = await media.createAVMetadataExtractor();
- // 设置fdSrc
- const fd = await fs.openSync(uri, fs.OpenMode.READ_ONLY);
- avMetadataExtractor.fdSrc = fd;
- // 获取元数据(promise模式)
- const metadata = await avMetadataExtractor.fetchMetadata();
- if(StrUtil.isNotEmpty(metadata.title)){
- musicName = metadata.title
- }
- if(musicName==undefined)
- musicName = file.name
- if(StrUtil.isNotEmpty(metadata.artist)){
- artist = metadata.artist
- }
- if(artist==undefined)
- artist = ''
- if(StrUtil.isNotEmpty(metadata.album)){
- album = metadata.album
- }
- if(StrUtil.isNotEmpty(metadata.duration)){
- if(metadata.duration)
- duration = convertSecondsToTime(metadata.duration.toString())
- }
- if(StrUtil.isNotEmpty(metadata.mimeType)){
- mimeType = metadata.mimeType
- }
- if(StrUtil.isNotEmpty(metadata.trackCount)){
- trackCount = metadata.trackCount
- }
- if(StrUtil.isNotEmpty(metadata.sampleRate)){
- sampleRate = metadata.sampleRate
- }
- let name = await MD5.digestSync(uri)
- if(isLoadPixelMap){
- // 获取专辑封面(promise模式)
- // pixelMap = await avMetadataExtractor.fetchAlbumCover();
- // // 释放资源(promise模式)
- // await avMetadataExtractor.release();
- pixelMap = await fetchAlbumCover(avMetadataExtractor)
- // console.info('onecold release success. name= '+musicName);
- if(pixelMap!==undefined&&pixelMap!==null){
- console.info('onecold pixelMap is not empty= '+musicName);
- imagePath = await ImageUtil.savePixelMap(pixelMap,context.filesDir,name)
- imagePath = fileUri.getUriFromPath(imagePath)
- }else{
- console.info('onecold pixelMap is empty= '+musicName);
- imagePath = ''
- // if(StrUtil.isNotEmpty(artist))
- // imagePath = await NetAxiosUtil.getLyricCover(musicName,artist)
- }
- }else{
- imagePath = context.filesDir + FileUtil.separator + name
- imagePath = fileUri.getUriFromPath(imagePath)
- }
- console.info('onecold release success. imagePath= '+imagePath);
- } catch (error) {
- console.error('Error during metadata extraction:', error);
- }
- } else {
- console.warn('AVMetadataExtractor capability is not supported.');
- }
- if(musicName==undefined)
- musicName = file.name
- item = new VideoItem(musicName,uri ,uri,type,videoSize,addTime,undefined,fileSize,
- imagePath,artist,album,file.name)
- item.duration = duration+'';
- item.mimeType = mimeType;
- item.trackCount = trackCount;
- item.sampleRate = sampleRate;
- item.isFav = 0;
- item.playCount = 0;
- })
- } catch (error) {
- console.error('uriGetAssetsFromFile failed with err: ' + JSON.stringify(error));
- }
- return item
- }
- private completionNum(num: number): string | number {
- if (num < 10) {
- return '0' + num;
- } else {
- return num;
- }
- }
- //根据字节获取大小
- static formatFSize(bytes:number):string {
- const units = ['Bytes', 'K', 'M', 'G'];
- let size = bytes;
- let unitIndex = 0;
- while (size >= 1024 && unitIndex < units.length - 1) {
- size /= 1024;
- unitIndex++;
- }
- // 保留两位小数, 四舍五入
- size = Math.round(size * 10) / 10;
- return size + units[unitIndex]
- }
- static gotoMarket(context:common.UIAbilityContext,bundleName:string) {
- const want: Want = {
- uri: `store://appgallery.huawei.com/app/detail?id=${bundleName}`
- };
- context.startAbility(want).then(()=>{
- //拉起成功
- }).catch(()=>{
- // 拉起失败
- });
- }
- static async doShare(item:VideoItem,context:common.UIAbilityContext){
- // 生成视频封面图
- const imagePackerApi: image.ImagePacker = image.createImagePacker();
- const buffer: ArrayBuffer = await (imagePackerApi.packing(await Utility.getFetchFrameByTime(item.filePath), {
- format: 'image/jpeg',
- quality: 30
- }) as Promise<ArrayBuffer>);
- // 构造ShareData,需配置一条有效数据信息
- let shareData: systemShare.SharedData = new systemShare.SharedData({
- utd: uniformTypeDescriptor.UniformDataType.MEDIA,
- uri: fileUri.getUriFromPath(item.filePath),
- title: item.name, // 不传title字段时,显示视频文件名
- // description: '好听的音乐', // 不传description字段时,显示视频大小
- thumbnail: new Uint8Array(buffer), // 优先使用传递的缩略图做预览 不传则默认使用视频第一帧画面做预览图
- });
- // 进行分享面板显示
- let controller: systemShare.ShareController = new systemShare.ShareController(shareData);
- // let context = getContext(this) as common.UIAbilityContext;
- controller.show(context, {
- selectionMode: systemShare.SelectionMode.SINGLE,
- previewMode: systemShare.SharePreviewMode.DETAIL,
- }).then(() => {
- console.info('ShareController show success.');
- }).catch((error: BusinessError) => {
- console.error(`ShareController show error. code: ${error.code}, message: ${error.message}`);
- });
- }
- //分享索引index的视频
- static async doShareMusic(item:VideoItem,context:common.UIAbilityContext){
- // 构造ShareData,需配置一条有效数据信息
- let shareData: systemShare.SharedData = new systemShare.SharedData({
- utd: uniformTypeDescriptor.UniformDataType.AUDIO,
- uri: fileUri.getUriFromPath(item.filePath),
- title: item.name, // 不传title字段时,显示视频文件名
- description: '好听的音乐', // 不传description字段时,显示视频大小
- });
- // 进行分享面板显示
- let controller: systemShare.ShareController = new systemShare.ShareController(shareData);
- // let context = getContext(this) as common.UIAbilityContext;
- controller.show(context, {
- selectionMode: systemShare.SelectionMode.SINGLE,
- previewMode: systemShare.SharePreviewMode.DETAIL,
- }).then(() => {
- console.info('ShareController show success.');
- }).catch((error: BusinessError) => {
- console.error(`ShareController show error. code: ${error.code}, message: ${error.message}`);
- });
- }
- static getNameList(localList:Array<VideoItem>){
- let list: Array<string> = [];
- for(let i=0;i<localList.length;i++){
- if(StrUtil.isNotEmpty(localList[i].name))
- list.push(localList[i].name);
- }
- return list
- }
- //根据type获取对应的播放列表(CommonConstants.TYPE_LOCAL:本地,CommonConstants.TYPE_Dir:私密视频)
- static getGlobalNameList(localList:Array<VideoItem>,type:number){
- let list: Array<string> = [];
- for(let i=0;i<localList.length;i++){
- if(localList[i].type === type){
- list.push(localList[i].name);
- }
- }
- return list
- }
- //根据type获取对应的播放列表(CommonConstants.TYPE_LOCAL:本地,CommonConstants.TYPE_LOCK:私密视频)
- static getGlobalList(localList:Array<VideoItem>,type:number){
- let list: Array<VideoItem> = [];
- for(let i=0;i<localList.length;i++){
- if(localList[i].type === type){
- list.push(localList[i]);
- }
- }
- return list
- }
- //根据filePath获取当前索引index
- static getCurIndexFromGlobalList(localList:Array<VideoItem>,filePath:string){
- let index: number = 0;
- for(let i=0;i<localList.length;i++){
- if(localList[i].filePath === filePath){
- index = i
- return index
- }
- }
- return index
- }
- //新的查询是否收藏的方法
- static getIsFav(favList: Array<VideoItem>,item:VideoItem|undefined){
- if(ArrayUtil.isEmpty(favList)){
- return false
- }
- if(item===undefined){
- return false
- }
- for(let i=0;i<favList.length;i++){
- if(favList[i].filePath === item.filePath&&favList[i].isFav===1){
- return true
- }
- }
- return false
- }
- static getIsFac(facList: Array<String>,item:VideoItem|undefined){
- if(ArrayUtil.isEmpty(facList)){
- return false
- }
- if(item===undefined){
- return false
- }
- for(let i=0;i<facList.length;i++){
- if(facList[i] === item.name||facList[i]===item.fileName){
- return true
- }
- }
- return false
- }
- static resourceToString(context:Context,resource:Resource){
- if(!context||!resource)
- return ''
- return context.resourceManager.getStringSync(resource).toString()
- }
- //根据type获取对应的播放列表(CommonConstants.TYPE_LOCAL:本地,CommonConstants.TYPE_LOCK:私密视频)
- static getGlobalMusicList(localList:Array<VideoItem>,type:number){
- let list: Array<VideoItem> = [];
- for(let i=0;i<localList.length;i++){
- if(localList[i].type === type){
- list.push(localList[i]);
- }
- }
- return list
- }
- static isHaoFreeTime():boolean{
- if(DateUtil.isWeekend()){
- return true
- }
- let str = DateUtil.getFormatDateStr(new Date(), 'HH')
- let a = Number(str);
- if(isNaN(a))
- return false
- // ToastUtil.showToast('a='+a)
- if (a >= 8 && a <13) {//白天
- return false;
- }
- if (a >= 13 && a <20) {//白天
- return false;
- }
- if (a >= 0 && a < 8) {//凌晨
- return true;
- }
- if (a >= 20 && a <= 24) {//晚上
- return true;
- }
- return false
- }
- static getMusisBg():Resource {
- let index = RandomUtil.randomNumber(0,9)
- LogUtil.info('getMusisBg index = '+index)
- return CommonConstants.musicBgList[index]
- }
- static getMusisBg2(index:number):Resource {
- const adjustedIndex = index % 10;
- LogUtil.info('getMusisBg adjustedIndex = '+adjustedIndex)
- return CommonConstants.musicBgList[adjustedIndex]
- }
- static getParentDirectory(filePath: string): string {
- // 使用正则表达式匹配路径分隔符(支持 Unix 和 Windows)
- const lastSlashIndex = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'));
- if (lastSlashIndex === -1) {
- return '';
- }
- return filePath.substring(0, lastSlashIndex);
- }
- static getFileDirName(filePath: string,rootPath:string): string{
- if(filePath===rootPath){
- return '首页'
- }
- let result = FileUtil.getFileName(filePath)
- if(StrUtil.isEmpty(result))
- return ''
- if(result.startsWith('.'))
- result = result.replace(/\./g, '')
- return result
- }
- // 开启沉浸式显示模式
- static async enableFullScreen() {
- const ctx = getContext()
- const win = await window.getLastWindow(ctx)
- win.setWindowLayoutFullScreen(true)
- const top = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM)
- AppStorage.setOrCreate('topHeight', px2vp(top.topRect.height))
- AppStorage.setOrCreate('bottomHeight', px2vp(top.bottomRect.height))
- }
- // 关闭沉浸式显示模式
- static async disableFullScreen() {
- const ctx = getContext()
- const win = await window.getLastWindow(ctx)
- win.setWindowLayoutFullScreen(false)
- AppStorage.setOrCreate('topHeight', 0)
- AppStorage.setOrCreate('bottomHeight', 0)
- }
- // 设置状态栏文字颜色为白色
- static async setStatusBarLight() {
- const ctx = getContext()
- const win = await window.getLastWindow(ctx)
- win.setWindowSystemBarProperties({
- statusBarContentColor: '#ffffff'
- })
- }
- // 设置状态栏文字颜色为黑色
- static async setStatusBarDark() {
- const ctx = getContext()
- const win = await window.getLastWindow(ctx)
- win.setWindowSystemBarProperties({
- statusBarContentColor: '#000000'
- })
- }
- // 优化点:完全基于Promise链的异步处理
- static async getAppName(context: Context): Promise<string> {
- try {
- // 1. 同步化BundleInfo获取
- const bundleInfo = await bundleManager.getBundleInfoForSelf(
- bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION
- );
- // 2. 安全获取labelId(新增空值校验)
- const labelId = bundleInfo.appInfo?.labelId;
- if (!labelId || labelId <= 0) {
- throw new Error("Invalid labelId: " + labelId);
- }
- // 3. 异步资源解析(替换危险的getStringSync)
- return await context.resourceManager.getStringValue(labelId);
- } catch (err) {
- console.error(`[${new Date().toISOString()}] AppName Error: CODE=${err.code}, MSG=${err.message}`);
- // 4. 多级降级策略
- return AppUtil.getBundleName() // 最终兜底
- }
- }
- //按名称升序
- static doSortListAscending( list:Array<VideoItem>){
- let options: Intl.CollatorOptions = {
- localeMatcher: "lookup",
- usage: "sort",
- sensitivity: "case" // 区分大小写
- };
- const collator = new Intl.Collator("zh-CN", options);
- list.sort((a, b) => {
- const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
- if (typeOrder !== 0) {
- return typeOrder;
- }
- const partsA = extractParts(a.name);
- const partsB = extractParts(b.name);
- const nonNumericComparison = collator.compare(partsA.nonNumeric, partsB.nonNumeric);
- if (nonNumericComparison !== 0) {
- return nonNumericComparison;
- }
- return partsA.numeric - partsB.numeric;
- });
- }
- //按名称降序
- static doSortListDescending(list:Array<VideoItem>){
- const options: Intl.CollatorOptions = {
- localeMatcher: "lookup",
- usage: "sort",
- sensitivity: "case" // 区分大小写
- };
- const collator = new Intl.Collator("zh-CN", options);
- list.sort((a, b) => {
- const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
- if (typeOrder !== 0) {
- return typeOrder;
- }
- const partsA = extractParts(a.name);
- const partsB = extractParts(b.name);
- const nonNumericComparison = collator.compare(partsB.nonNumeric, partsA.nonNumeric);
- if (nonNumericComparison !== 0) {
- return nonNumericComparison;
- }
- return partsB.numeric - partsA.numeric;
- });
- }
- }
- interface PathStat {
- path: string;
- isDirectory: boolean;
- }
- async function isDirectory(filePath: string): Promise<boolean> {
- try {
- const stat = await fs.stat(filePath);
- return stat.isDirectory();
- } catch (error) {
- console.error('Error getting file stat:', error);
- return false;
- }
- }
- //排序模式参数
- interface VideoNameParts {
- nonNumeric: string;
- numeric: number;
- }
- function extractParts(name: string): VideoNameParts {
- const match = name.match(/^(\D*)(\d*)/);
- return {
- nonNumeric: match?.[1] || '',
- numeric: parseInt(match?.[2] || '0', 10)
- };
- }
- function getInstallTime(): number | null {
- // 从本地存储中获取安装时间
- return PreferencesUtil.getNumberSync('installTime')
- }
- function setInstallTime(time: number) {
- // 将安装时间存储到本地存储中
- PreferencesUtil.putSync('installTime',time)
- }
- function fetchAlbumCover(avMetadataExtractor: media.AVMetadataExtractor): Promise<image.PixelMap | null> {
- return new Promise((resolve, reject) => {
- avMetadataExtractor.fetchAlbumCover((error: BusinessError, pixelMap: image.PixelMap) => {
- if (error) {
- console.error(`Failed to fetch AlbumCover, error = ${JSON.stringify(error)}`);
- resolve(null);
- } else {
- resolve(pixelMap);
- }
- avMetadataExtractor.release();
- });
- });
- }
- //排序类型
- function getTypeOrder(type: number) {
- switch (type) {
- case CommonConstants.TYPE_IS_DIR:
- return 1; // First
- case CommonConstants.TYPE_IS_CSJAD:
- return 2; // Middle
- case CommonConstants.TYPE_LOCAL:
- return 3; // Last
- default:
- return 4; // Unknown types, if any, go last
- }
- }
- function convertSecondsToTime(secondsStr: string): string {
- if (!secondsStr || isNaN(Number(secondsStr))) {
- return "00:00";
- }
- let seconds = parseInt(secondsStr, 10);
- seconds = Math.floor(seconds / 1000);
- const hours = Math.floor(seconds / 3600);
- const minutes = Math.floor((seconds % 3600) / 60);
- const secs = seconds % 60;
- const formatNumber = (num: number) => num.toString().padStart(2, '0');
- if (hours > 0) {
- return `${formatNumber(hours)}:${formatNumber(minutes)}:${formatNumber(secs)}`;
- } else {
- return `${formatNumber(minutes)}:${formatNumber(secs)}`;
- }
- }
|