• 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 === 'p7b') || (suffix === 'spc')) {
55      this.optType = CMModelOptType.CM_MODEL_OPT_USER_CA_P7B;
56    } else if (((suffix === 'p12') || (suffix === 'pfx')) &&
57      AppStorage.get('installUserCred') === true) {
58      this.optType = CMModelOptType.CM_MODEL_OPT_APP_CRED;
59    } else if (((suffix === 'p12') || (suffix === 'pfx')) &&
60      AppStorage.get('installSystemCred') === true) {
61      this.optType = CMModelOptType.CM_MODEL_OPT_SYSTEM_CRED;
62    } else {
63      console.debug(TAG, 'The file type is not supported. suffix: ' + suffix);
64    }
65  }
66
67  getFileDataFromUri(uri: string, callback: Function): void {
68    FileIoModel.getMediaFileData(uri, (data: Uint8Array) => {
69      callback(data);
70    });
71  }
72
73  checkCertNameLength(uri: string, alias: string, suffix: string, pwd: string): Promise<number> {
74    return new Promise((resolve) => {
75      this.updateCertFileType(suffix);
76      this.getFileDataFromUri(uri, (data: Uint8Array) => {
77        certManagerModel.installCertOrCred(this.optType, alias, data, pwd, (errCode: CMModelErrorCode) => {
78          if (errCode === CMModelErrorCode.CM_MODEL_ERROR_ALIAS_LENGTH_REACHED_LIMIT) {
79            resolve(errCode)
80          } else {
81            resolve(0)
82          }
83        })
84      })
85    })
86  }
87
88  installSuccessTips(): void {
89    try {
90      promptAction.showToast({
91        message: this.optType === CMModelOptType.CM_MODEL_OPT_USER_CA ?
92        $r('app.string.Install_Cert_Success') : $r('app.string.Install_Cred_Success'),
93        duration: DURATION,
94        bottom: bottomNum
95      })
96    } catch (err) {
97      let e: BusinessError = err as BusinessError;
98      console.error(TAG, 'show result failed, message: ' + e.message + ', code: ' + e.code)
99    }
100  }
101
102  errorFormatTips(): void {
103    AlertDialog.show({
104      message: $r('app.string.Install_ERROR_INCORRECT_FORMAT'),
105      autoCancel: true,
106      alignment: DialogAlignment.Bottom,
107      offset: {
108        dx: $r('app.float.wh_value_0'), dy: $r('app.float.wh_value_0')
109      },
110      gridCount: gridCountNum,
111      primaryButton: {
112        value: $r('app.string.OK'),
113        action: () => {
114        }
115      },
116    })
117  }
118
119  maxQuantityReachedTips(): void {
120    AlertDialog.show({
121      message: $r('app.string.Install_Error_MAX_QUANTITY_REACHED'),
122      autoCancel: true,
123      alignment: DialogAlignment.Bottom,
124      offset: {
125        dx: $r('app.float.wh_value_0'), dy: $r('app.float.wh_value_0')
126      },
127      gridCount: gridCountNum,
128      primaryButton: {
129        value: $r('app.string.OK'),
130        action: () => {
131          router.back({
132            url: 'pages/certManagerFa'
133          })
134        }
135      },
136    })
137  }
138
139  installFailedTips(): void {
140    try {
141      promptAction.showToast({
142        message: this.optType === CMModelOptType.CM_MODEL_OPT_USER_CA ?
143        $r('app.string.Install_Cert_Failed') : $r('app.string.Install_Cred_Failed'),
144        duration: DURATION,
145        bottom: bottomNum
146      })
147    } catch (err) {
148      let e: BusinessError = err as BusinessError;
149      console.error(TAG, 'show result failed, message: ' + e.message + ', code: ' + e.code)
150    }
151  }
152
153  installCert(uri: string, alias: string, suffix: string, isNeedJumpBack: boolean): Promise<CMModelErrorCode> {
154    return new Promise((resolve => {
155      this.updateCertFileType(suffix);
156      this.getFileDataFromUri(uri, (data: Uint8Array) => {
157        certManagerModel.installCertOrCred(this.optType, alias, data,
158          GlobalContext.getContext().getPwdStore().getCertPwd(), (errCode: CMModelErrorCode) => {
159            GlobalContext.getContext().getPwdStore().clearCertPwd();
160            this.handleInstallResult(errCode, isNeedJumpBack);
161            resolve(errCode);
162          });
163      });
164    }));
165  }
166
167  private handleInstallResult(errCode: CMModelErrorCode, isNeedJumpBack: boolean) {
168    console.info(TAG + 'installCertOrCred result: ' + JSON.stringify(errCode));
169    let isNeedJumpHomePage = true;
170    switch (errCode) {
171      case CMModelErrorCode.CM_MODEL_ERROR_SUCCESS:
172        this.installSuccessTips();
173        break;
174
175      case CMModelErrorCode.CM_MODEL_ERROR_INCORRECT_FORMAT:
176        this.errorFormatTips();
177        break;
178
179      case CMModelErrorCode.CM_MODEL_ERROR_MAX_QUANTITY_REACHED:
180        this.maxQuantityReachedTips();
181        break;
182
183      case CMModelErrorCode.CM_MODEL_ERROR_PASSWORD_ERR:
184        isNeedJumpHomePage = false;
185        break;
186
187      default:
188        this.installFailedTips();
189        break;
190    }
191    if (!isNeedJumpHomePage || !isNeedJumpBack) {
192      return;
193    }
194    router.clear();
195    router.replaceUrl({
196      url: 'pages/certManagerFa'
197    });
198  }
199}