• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/**
2 * Copyright (c) 2022-2024 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 certManagerModel from '../model/CertMangerModel';
17import FileIoModel from '../model/FileIoModel';
18import { CMModelErrorCode, CMModelOptType } from '../model/CertMangerModel';
19import router from '@ohos.router';
20import { GlobalContext } from '../common/GlobalContext';
21import promptAction from '@ohos.promptAction';
22import { BusinessError } from '@ohos.base';
23
24const TAG = 'CMInstallPresenter: ';
25const DURATION = 2000;
26const gridCountNum: number = 4;
27const bottomNum: number = 100;
28
29export default class CmInstallPresenter {
30  private static sInstance: CmInstallPresenter;
31  private optType: CMModelOptType = CMModelOptType.CM_MODEL_OPT_UNKNOWN;
32
33  public static getInstance(): CmInstallPresenter {
34    if (CmInstallPresenter.sInstance == null) {
35      CmInstallPresenter.sInstance = new CmInstallPresenter();
36    }
37    return CmInstallPresenter.sInstance;
38  }
39
40  onAboutToAppear(): void {
41
42  }
43
44  aboutToDisappear(): void {
45    this.optType = CMModelOptType.CM_MODEL_OPT_UNKNOWN;
46    AppStorage.setOrCreate('installUserCred',false);
47    AppStorage.setOrCreate('installSystemCred',false);
48  }
49
50  updateCertFileType(suffix: string): void {
51    console.debug(TAG + 'updateCertFileType suffix: ' + suffix);
52    if ((suffix === 'cer') || (suffix === 'pem') || (suffix === 'crt') || (suffix === 'der')) {
53      this.optType = CMModelOptType.CM_MODEL_OPT_USER_CA;
54    } else if (((suffix === 'p12') || (suffix === 'pfx')) &&
55      AppStorage.get('installUserCred') === true) {
56      this.optType = CMModelOptType.CM_MODEL_OPT_APP_CRED;
57    } else if (((suffix === 'p12') || (suffix === 'pfx')) &&
58      AppStorage.get('installSystemCred') === true) {
59      this.optType = CMModelOptType.CM_MODEL_OPT_SYSTEM_CRED;
60    } else {
61      console.debug(TAG, 'The file type is not supported. suffix: ' + suffix);
62    }
63  }
64
65  getFileDataFromUri(uri: string, callback: Function): void {
66    FileIoModel.getMediaFileData(uri, (data: Uint8Array) => {
67      callback(data);
68    });
69  }
70
71  checkCertNameLength(uri: string, alias: string, suffix: string, pwd: string): Promise<number> {
72    return new Promise((resolve) => {
73      this.updateCertFileType(suffix);
74      this.getFileDataFromUri(uri, (data: Uint8Array) => {
75        certManagerModel.installCertOrCred(this.optType, alias, data, pwd, (errCode: CMModelErrorCode) => {
76          if (errCode === CMModelErrorCode.CM_MODEL_ERROR_ALIAS_LENGTH_REACHED_LIMIT) {
77            resolve(errCode)
78          } else {
79            resolve(0)
80          }
81        })
82      })
83    })
84  }
85
86  installSuccessTips(): void {
87    try {
88      promptAction.showToast({
89        message: this.optType === CMModelOptType.CM_MODEL_OPT_USER_CA ?
90        $r('app.string.Install_Cert_Success') : $r('app.string.Install_Cred_Success'),
91        duration: DURATION,
92        bottom: bottomNum
93      })
94    } catch (err) {
95      let e: BusinessError = err as BusinessError;
96      console.error(TAG, 'show result failed, message: ' + e.message + ', code: ' + e.code)
97    }
98  }
99
100  errorFormatTips(): void {
101    AlertDialog.show({
102      message: $r('app.string.Install_ERROR_INCORRECT_FORMAT'),
103      autoCancel: true,
104      alignment: DialogAlignment.Bottom,
105      offset: {
106        dx: $r('app.float.wh_value_0'), dy: $r('app.float.wh_value_0')
107      },
108      gridCount: gridCountNum,
109      primaryButton: {
110        value: $r('app.string.OK'),
111        action: () => {
112        }
113      },
114    })
115  }
116
117  maxQuantityReachedTips(): void {
118    AlertDialog.show({
119      message: $r('app.string.Install_Error_MAX_QUANTITY_REACHED'),
120      autoCancel: true,
121      alignment: DialogAlignment.Bottom,
122      offset: {
123        dx: $r('app.float.wh_value_0'), dy: $r('app.float.wh_value_0')
124      },
125      gridCount: gridCountNum,
126      primaryButton: {
127        value: $r('app.string.OK'),
128        action: () => {
129          router.back({
130            url: 'pages/certManagerFa'
131          })
132        }
133      },
134    })
135  }
136
137  installFailedTips(): void {
138    try {
139      promptAction.showToast({
140        message: this.optType === CMModelOptType.CM_MODEL_OPT_USER_CA ?
141        $r('app.string.Install_Cert_Failed') : $r('app.string.Install_Cred_Failed'),
142        duration: DURATION,
143        bottom: bottomNum
144      })
145    } catch (err) {
146      let e: BusinessError = err as BusinessError;
147      console.error(TAG, 'show result failed, message: ' + e.message + ', code: ' + e.code)
148    }
149  }
150
151  installCert(uri: string, alias: string, suffix: string, isNeedJumpBack: boolean): Promise<CMModelErrorCode> {
152    return new Promise((resolve => {
153      this.updateCertFileType(suffix);
154      this.getFileDataFromUri(uri, (data: Uint8Array) => {
155        certManagerModel.installCertOrCred(this.optType, alias, data,
156          GlobalContext.getContext().getPwdStore().getCertPwd(), (errCode: CMModelErrorCode) => {
157            GlobalContext.getContext().getPwdStore().clearCertPwd();
158            this.handleInstallResult(errCode, isNeedJumpBack);
159            resolve(errCode);
160          });
161      });
162    }));
163  }
164
165  private handleInstallResult(errCode: CMModelErrorCode, isNeedJumpBack: boolean) {
166    console.info(TAG + 'installCertOrCred result: ' + JSON.stringify(errCode));
167    let isNeedJumpHomePage = true;
168    switch (errCode) {
169      case CMModelErrorCode.CM_MODEL_ERROR_SUCCESS:
170        this.installSuccessTips();
171        break;
172
173      case CMModelErrorCode.CM_MODEL_ERROR_INCORRECT_FORMAT:
174        this.errorFormatTips();
175        break;
176
177      case CMModelErrorCode.CM_MODEL_ERROR_MAX_QUANTITY_REACHED:
178        this.maxQuantityReachedTips();
179        break;
180
181      case CMModelErrorCode.CM_MODEL_ERROR_PASSWORD_ERR:
182        isNeedJumpHomePage = false;
183        break;
184
185      default:
186        this.installFailedTips();
187        break;
188    }
189    if (!isNeedJumpHomePage || !isNeedJumpBack) {
190      return;
191    }
192    router.clear();
193    router.replaceUrl({
194      url: 'pages/certManagerFa'
195    });
196  }
197}