1/* 2 * Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import photoAccessHelper from '@ohos.file.photoAccessHelper'; 17import DateTimeUtil from '../utlis/DateTimeUtil'; 18import { GlobalContext } from '../utlis/GlobalContext'; 19import common from '@ohos.app.ability.common'; 20import Logger from '../utlis/Logger'; 21 22const TAG = '[MediaModel]'; 23 24type FileInfo = { 25 prefix: string; 26 suffix: string; 27}; 28 29export default class MediaModel { 30 private accessHelper: photoAccessHelper.PhotoAccessHelper = undefined; 31 private static mediaInstance: MediaModel = undefined; 32 33 constructor() { 34 let cameraContext: common.UIAbilityContext = GlobalContext.getContext().getCameraAbilityContext(); 35 this.accessHelper = photoAccessHelper.getPhotoAccessHelper(cameraContext); 36 } 37 38 public static getMediaInstance(): MediaModel { 39 if (this.mediaInstance === undefined) { 40 this.mediaInstance = new MediaModel(); 41 } 42 return this.mediaInstance; 43 } 44 45 async createAndGetUri(mediaType: photoAccessHelper.PhotoType): Promise<photoAccessHelper.PhotoAsset> { 46 let dateTimeUtil: DateTimeUtil = new DateTimeUtil(); 47 let info: FileInfo = this.getInfoFromMediaType(mediaType); 48 let name: string = `${dateTimeUtil.getDate()}_${dateTimeUtil.getTime()}`; 49 let displayName: string = `${info.prefix}${name}${info.suffix}`; 50 Logger.info(TAG, `displayName = ${displayName},mediaType = ${mediaType}`); 51 let fileAsset: photoAccessHelper.PhotoAsset = await this.accessHelper.createAsset(displayName); 52 return fileAsset; 53 } 54 55 async getFdPath(fileAsset: photoAccessHelper.PhotoAsset): Promise<number> { 56 let fd: number = await fileAsset.open('rw'); 57 Logger.info(TAG, `fd = ${fd}`); 58 return fd; 59 } 60 61 getInfoFromMediaType(mediaType: photoAccessHelper.PhotoType): FileInfo { 62 let fileInfo: FileInfo = { 63 prefix: '', 64 suffix: '' 65 }; 66 switch (mediaType) { 67 case photoAccessHelper.PhotoType.IMAGE: 68 fileInfo.prefix = 'IMG_'; 69 fileInfo.suffix = '.jpg'; 70 break; 71 case photoAccessHelper.PhotoType.VIDEO: 72 fileInfo.prefix = 'VID_'; 73 fileInfo.suffix = '.mp4'; 74 break; 75 default: 76 break; 77 } 78 return fileInfo; 79 } 80} 81