1// @ts-nocheck 2/* 3 * Copyright (c) 2023 Huawei Device Co., Ltd. 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17import dataStorage from '@ohos.data.storage'; 18 19const TAG: string = 'PreferencesService' 20 21export enum PersistType { 22 NEVER, 23 FOREVER, 24 FOR_AWHILE, 25 TILL_EXIT 26} 27 28export class PreferencesService { 29 private static modeStorage 30 31 public static getInstance(): PreferencesService { 32 if (!globalThis?.sInstancePreferencesService) { 33 globalThis.sInstancePreferencesService = new PreferencesService() 34 let filePath = globalThis.cameraAbilityContext.filesDir 35 PreferencesService.modeStorage = dataStorage.getStorageSync(filePath + '/mode_persist_values') 36 } 37 return globalThis.sInstancePreferencesService 38 } 39 40 getModeValue(persistType: PersistType, defaultValue: any) { 41 if (persistType === PersistType.FOR_AWHILE && this.isModeExpire()) { 42 return defaultValue 43 } 44 return PreferencesService.modeStorage.getSync(this.getModePersistKey(persistType, 'BASE'), defaultValue) 45 } 46 47 putModeValue(persistType, value: any) { 48 if (persistType === PersistType.FOR_AWHILE) { 49 PreferencesService.modeStorage.putSync(this.getModePersistKey(persistType, 'Timestamp'), new Date().getTime()) 50 } 51 PreferencesService.modeStorage.putSync(this.getModePersistKey(persistType, 'BASE'), value) 52 } 53 54 flush(): void { 55 PreferencesService.modeStorage.putSync(this.getModePersistKey(PersistType.FOR_AWHILE, 'Timestamp'), new Date().getTime()) 56 this.flushMode() 57 } 58 59 flushMode(): void { 60 PreferencesService.modeStorage.flushSync() 61 } 62 63 private getModeTimestamp(persistType: PersistType, defaultValue: any): any { 64 return PreferencesService.modeStorage.getSync(this.getModePersistKey(persistType, 'Timestamp'), defaultValue) 65 } 66 67 private isModeExpire(): boolean { 68 return (new Date().getTime() - this.getModeTimestamp(PersistType.FOR_AWHILE, 0)) > 15*60*1000 69 } 70 71 private getModePersistKey(persistType: PersistType, item: string): string { 72 return 'mode_' + persistType + '_' + item 73 } 74}