• 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 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 =
33        dataStorage.getStorageSync(GlobalContext.get().getCameraAbilityContext().filesDir + '/mode_persist_values');
34    }
35    return globalThis.sInstancePreferencesService;
36  }
37
38  getModeValue(persistType: PersistType, defaultValue: number): number {
39    if (persistType === PersistType.FOR_AWHILE && this.isModeExpire()) {
40      return defaultValue;
41    }
42    return PreferencesService.modeStorage.getSync(this.getModePersistKey(persistType, 'BASE'), defaultValue);
43  }
44
45  putModeValue(persistType, value: any): void {
46    if (persistType === PersistType.FOR_AWHILE) {
47      PreferencesService.modeStorage.putSync(this.getModePersistKey(persistType, 'Timestamp'), new Date().getTime());
48    }
49    PreferencesService.modeStorage.putSync(this.getModePersistKey(persistType, 'BASE'), value);
50  }
51
52  flush(): void {
53    PreferencesService.modeStorage.putSync(this.getModePersistKey(PersistType.FOR_AWHILE, 'Timestamp'),
54      new Date().getTime());
55    this.flushMode();
56  }
57
58  flushMode(): void {
59    PreferencesService.modeStorage.flushSync();
60  }
61
62  private getModeTimestamp(persistType: PersistType, defaultValue: any): any {
63    return PreferencesService.modeStorage.getSync(this.getModePersistKey(persistType, 'Timestamp'), defaultValue);
64  }
65
66  private isModeExpire(): boolean {
67    return (new Date().getTime() - this.getModeTimestamp(PersistType.FOR_AWHILE, 0)) > 15 * 60 * 1000;
68  }
69
70  private getModePersistKey(persistType: PersistType, item: string): string {
71    return 'mode_' + persistType + '_' + item;
72  }
73}