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 dataStorage from '@ohos.data.storage'; 17import { GlobalContext } from '../../utils/GlobalContext'; 18 19export enum PersistType { 20 NEVER, 21 FOREVER, 22 FOR_AWHILE, 23 TILL_EXIT 24} 25 26export class PreferencesService { 27 private static modeStorage; 28 29 public static getInstance(): PreferencesService { 30 if (!globalThis?.sInstancePreferencesService) { 31 globalThis.sInstancePreferencesService = new PreferencesService(); 32 PreferencesService.modeStorage = dataStorage.getStorageSync(GlobalContext.get().getCameraAbilityContext().filesDir + '/mode_persist_values'); 33 } 34 return globalThis.sInstancePreferencesService; 35 } 36 37 getModeValue(persistType: PersistType, defaultValue: number): number { 38 if (persistType === PersistType.FOR_AWHILE && this.isModeExpire()) { 39 return defaultValue; 40 } 41 return PreferencesService.modeStorage.getSync(this.getModePersistKey(persistType, 'BASE'), defaultValue); 42 } 43 44 putModeValue(persistType, value: any): void { 45 if (persistType === PersistType.FOR_AWHILE) { 46 PreferencesService.modeStorage.putSync(this.getModePersistKey(persistType, 'Timestamp'), new Date().getTime()); 47 } 48 PreferencesService.modeStorage.putSync(this.getModePersistKey(persistType, 'BASE'), value); 49 } 50 51 flush(): void { 52 PreferencesService.modeStorage.putSync(this.getModePersistKey(PersistType.FOR_AWHILE, 'Timestamp'), new Date().getTime()); 53 this.flushMode(); 54 } 55 56 flushMode(): void { 57 PreferencesService.modeStorage.flushSync(); 58 } 59 60 private getModeTimestamp(persistType: PersistType, defaultValue: any): any { 61 return PreferencesService.modeStorage.getSync(this.getModePersistKey(persistType, 'Timestamp'), defaultValue); 62 } 63 64 private isModeExpire(): boolean { 65 return (new Date().getTime() - this.getModeTimestamp(PersistType.FOR_AWHILE, 0)) > 15 * 60 * 1000; 66 } 67 68 private getModePersistKey(persistType: PersistType, item: string): string { 69 return 'mode_' + persistType + '_' + item; 70 } 71}