1/* 2 * Copyright (c) 2022-2023 Huawei Device 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 fileShare from '@ohos.fileshare'; 17import wantConstant from '@ohos.ability.wantConstant'; 18import { Log } from '../../../utils/Log'; 19import { UserFileManagerAccess } from '../../../access/UserFileManagerAccess'; 20import { MediaItem } from './MediaItem'; 21 22const TAG: string = 'common_SelectUtil'; 23 24export class SelectUtil { 25 static getUriArray(selectedPhotos: Set<string>): Array<string> { 26 let uriArray = new Array<string>(); 27 if (selectedPhotos == undefined) { 28 return uriArray; 29 } 30 selectedPhotos.forEach((uri) => { 31 uriArray.push(uri); 32 }) 33 return uriArray; 34 } 35 36 static getCountOfMedia(uriArray: Array<string>, selectedMap: Map<string, MediaItem>): Promise<Array<number>> { 37 let result = [0, 0]; 38 if (uriArray === null || uriArray === undefined || uriArray.length <= 0) { 39 Log.info(TAG, 'uriArray is null or empty!'); 40 return new Promise((resolve): void => { 41 resolve(result); 42 }); 43 } 44 45 if (selectedMap === undefined || selectedMap.size <= 0) { 46 Log.info(TAG, 'selectedMap is null or empty!'); 47 return new Promise((resolve): void => { 48 resolve(result); 49 }); 50 } 51 52 let imageCount: number = 0; 53 let videoCount: number = 0; 54 for (let i = 0; i < uriArray.length; i++) { 55 let mediaItem: MediaItem = selectedMap.get(uriArray[i]); 56 if (mediaItem?.mediaType === UserFileManagerAccess.MEDIA_TYPE_IMAGE) { 57 imageCount++; 58 } else if (mediaItem?.mediaType === UserFileManagerAccess.MEDIA_TYPE_VIDEO) { 59 videoCount++; 60 } 61 } 62 result = [imageCount, videoCount]; 63 return new Promise((resolve): void => { 64 resolve(result); 65 }); 66 } 67 68 static async grantPermissionForUris(uris: Array<string>, bundleName: string): Promise<void> { 69 Log.info(TAG, `start uris grant. bundleName: ${bundleName}`); 70 let promises: Array<Promise<void>> = []; 71 for (let uri of uris) { 72 promises.push(SelectUtil.grantPermissionForUri(uri, bundleName)); 73 } 74 await Promise.all(promises); 75 } 76 77 private static async grantPermissionForUri(uri: string, bundleName: string): Promise<void> { 78 Log.debug(TAG, `start uri grant. uri: ${uri}`); 79 try { 80 await fileShare.grantUriPermission(uri, bundleName, wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION); 81 } catch (err) { 82 Log.error(TAG, `grant permission error: ${JSON.stringify(err)}`); 83 } 84 } 85}