• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (C) 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 photoAccessHelper from '@ohos.file.photoAccessHelper';
17import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
18import bundleManager from '@ohos.bundle.bundleManager';
19import dataSharePredicates from '@ohos.data.dataSharePredicates';
20
21const photoType = photoAccessHelper.PhotoType;
22const photoKeys = photoAccessHelper.PhotoKeys;
23const albumKeys = photoAccessHelper.AlbumKeys;
24const albumType = photoAccessHelper.AlbumType;
25const albumSubtype = photoAccessHelper.AlbumSubtype;
26const DEFAULT_SLEEP_TIME = 10;
27export async function sleep(times = DEFAULT_SLEEP_TIME) : Promise<void> {
28  await new Promise(res => setTimeout(res, times));
29};
30
31export function fetchAllOption() : photoAccessHelper.FetchOptions {
32  const predicates = new dataSharePredicates.DataSharePredicates();
33  const ops : photoAccessHelper.FetchOptions = {
34    fetchColumns: [],
35    predicates: predicates
36  };
37  return ops;
38};
39
40export function fetchOption(testNum, key, value) : photoAccessHelper.FetchOptions {
41  const predicates = new dataSharePredicates.DataSharePredicates();
42  predicates.equalTo(key, value);
43  const ops : photoAccessHelper.FetchOptions = {
44    fetchColumns: [],
45    predicates: predicates
46  };
47  console.info(`${testNum} queryOps: ${key} = ${value}`);
48  return ops;
49};
50
51export function albumFetchOption(testNum, key, value) : photoAccessHelper.FetchOptions {
52  const predicates = new dataSharePredicates.DataSharePredicates();
53  predicates.equalTo(key, value);
54  const ops : photoAccessHelper.FetchOptions = {
55    fetchColumns: [],
56    predicates: predicates
57  };
58  console.info(`${testNum} queryOps: ${key} = ${value}`);
59  return ops;
60};
61
62export function photoFetchOption(testNum, key, value) : photoAccessHelper.FetchOptions {
63  const predicates = new dataSharePredicates.DataSharePredicates();
64  predicates.equalTo(key, value);
65  const ops : photoAccessHelper.FetchOptions = {
66    fetchColumns: [
67      photoKeys.URI,
68      photoKeys.PHOTO_TYPE,
69      photoKeys.DISPLAY_NAME,
70      photoKeys.DATE_ADDED,
71      photoKeys.DATE_MODIFIED,
72      photoKeys.DURATION,
73      photoKeys.WIDTH,
74      photoKeys.HEIGHT,
75      photoKeys.DATE_TAKEN,
76      photoKeys.ORIENTATION,
77      photoKeys.FAVORITE,
78      photoKeys.SIZE,
79      photoKeys.TITLE,
80      photoKeys.POSITION,
81      photoKeys.DATE_TRASHED,
82      photoKeys.HIDDEN,
83      photoKeys.CAMERA_SHOT_KEY,
84      photoKeys.USER_COMMENT,
85      'all_exif',
86    ],
87    predicates: predicates
88  };
89  console.info(`${testNum} queryOps: ${key} = ${value}`);
90  return ops;
91};
92
93export async function getPermission(name = 'ohos.acts.multimedia.photoaccess') : Promise<void> {
94  try {
95    console.info('getPermission start', name);
96    let permissionState = new Map();
97    const permissions = [
98      'ohos.permission.MEDIA_LOCATION',
99      'ohos.permission.READ_IMAGEVIDEO',
100      'ohos.permission.WRITE_IMAGEVIDEO',
101    ];
102
103    const atManager = abilityAccessCtrl.createAtManager();
104    const appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT;
105    const userId = 100;
106    const appInfo = await bundleManager.getApplicationInfo(name, appFlags, userId);
107    const tokenID = appInfo.accessTokenId;
108    for (const permission of permissions) {
109      console.info('getPermission permission: ' + permission);
110      try {
111        await atManager.grantUserGrantedPermission(tokenID, permission, 1);
112      } catch (error) {
113        console.info(`getPermission ${permission} failed`);
114      }
115      permissionState.set(permission, await atManager.verifyAccessToken(tokenID, permission));
116    }
117    permissionState.forEach((value, key, map) => {
118      if (value !== 0) {
119        console.info(`getPermission failed; permission: ${key}, state: ${value}`);
120      }
121    });
122    console.info('getPermission end');
123  } catch (error) {
124    console.info(`getPermission failed, error: ${error}`);
125  }
126};
127
128export function isNum(value) : boolean {
129  return typeof value === 'number' && !isNaN(value);
130};
131
132export function getAssetId(uri) : string {
133  const tag = 'Photo/';
134  const index = uri.indexOf(tag);
135  let str = uri.substring(index + tag.length);
136  console.info(`getAssetId str: ${str}`);
137  return str;
138}
139
140export function getAlbumId(uri) : string {
141  const index = uri.lastIndexOf('/');
142  let str = uri.substring(index + 1);
143  console.info(`getAlbumId str: ${str}`);
144  return str;
145}
146
147export function genRadomStr(len: number) : string {
148  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
149  let randomStr = '';
150  for (let i = 0; i < len; i++) {
151    randomStr += chars.charAt(Math.floor(Math.random() * chars.length));
152  }
153  return randomStr;
154}
155
156export async function createUserAlbum(testNum, albumName) : Promise<photoAccessHelper.Album> {
157  console.info(`${testNum} createUserAlbum albumName: ${albumName}`);
158  let album: photoAccessHelper.Album;
159  try {
160    const helper = photoAccessHelper.getPhotoAccessHelper(globalThis.abilityContext);
161    album = await helper.createAlbum(albumName);
162    console.info(`${testNum} createUserAlbum suc`);
163  } catch (error) {
164    console.info(`Failed to createUserAlbum! error: ${error}`);
165    throw error;
166  }
167
168  return new Promise((resolve, reject) => {
169    resolve(album);
170  });
171}
172
173export async function getFileAsset(testNum, fetchOps) : Promise<photoAccessHelper.PhotoAsset> {
174  let asset: photoAccessHelper.PhotoAsset;
175  try {
176    const helper = photoAccessHelper.getPhotoAccessHelper(globalThis.abilityContext);
177    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset>;
178    fetchResult = await helper.getAssets(fetchOps);
179    console.info(`${testNum} getFileAsset fetchResult: ${fetchResult.getCount()}`);
180    asset = await fetchResult.getFirstObject();
181    fetchResult.close();
182  } catch (error) {
183    console.info(`${testNum} getFileAsset error: ${error}`);
184    throw error;
185  }
186
187  return new Promise((resolve, reject) => {
188    resolve(asset);
189  });
190}
191
192export function getFileAssetFetchResult() : photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> {
193  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset>;
194  return fetchResult;
195}
196
197export function getAlbumFetchResult() : photoAccessHelper.FetchResult<photoAccessHelper.Album> {
198  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album>;
199  return fetchResult;
200}
201
202export function checkUserAlbum(expect, testNum, album, expectedName, expectedCover) : void {
203  console.info(`${testNum} checkUserAlbum album.albumName: ${album.albumName}, expectedName: ${expectedName}`);
204  expect(album.albumType).assertEqual(albumType.USER);
205  expect(album.albumSubtype).assertEqual(albumSubtype.USER_GENERIC);
206  expect(album.albumName).assertEqual(expectedName);
207  if (expectedCover === '') {
208    expect(album.coverUri).assertEqual('');
209  } else {
210    expect(album.coverUri).assertEqual(expectedCover);
211  }
212  expect(album.albumUri !== '').assertEqual(true);
213  expect(album.count).assertEqual(0);
214}
215
216export function checkSystemAlbum(expect, testNum, album, expectedSubType) : void {
217  try {
218    console.info(`${testNum} checkSystemAlbum expectedSubType: ${expectedSubType}`);
219    expect(album.albumType).assertEqual(albumType.SYSTEM);
220    expect(album.albumSubtype).assertEqual(expectedSubType);
221    expect(album.albumName).assertEqual('');
222    expect(album.albumUri !== '').assertEqual(true);
223  } catch (error) {
224    console.info(`Failed to delete all user albums! error: ${error}`);
225    throw error;
226  }
227}
228
229export {
230  photoType,
231  photoKeys,
232  albumKeys,
233  albumType,
234  albumSubtype,
235};