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 picker from '@ohos.file.picker';
17import router from '@ohos.router';
18import certManagerModel from '../model/CertMangerModel';
19import FileIoModel from '../model/FileIoModel';
20import { CMModelErrorCode, CMModelOptType } from '../model/CertMangerModel';
21import { BusinessError } from '@ohos.base';
22import { RouterFileVo, RouterAppUidVo } from '../model/CertManagerVo/RouterInfoVo';
23import checkUserAuthModel from '../model/CheckUserAuthModel';
24import CmInstallPresenter from './CmInstallPresenter';
25
26const TAG = 'CMFaPresenter: ';
27const gridCountNum: number = 4;
28
29export default class CmFaPresenter {
30  private static sInstance: CmFaPresenter;
31
32  public static getInstance(): CmFaPresenter {
33    if (CmFaPresenter.sInstance == null) {
34      CmFaPresenter.sInstance = new CmFaPresenter();
35    }
36    return CmFaPresenter.sInstance;
37  }
38
39  onAboutToAppear(): void {
40
41  }
42
43  aboutToDisappear(): void {
44  }
45
46  unrecognizedFileTips(): void {
47    AlertDialog.show({
48      message: $r('app.string.Install_Error_NOT_FOUND'),
49      autoCancel: true,
50      alignment: DialogAlignment.Bottom,
51      offset: {
52        dx: $r('app.float.wh_value_0'), dy: $r('app.float.wh_value_0')
53      },
54      gridCount: gridCountNum,
55      primaryButton: {
56        value: $r('app.string.OK'),
57        action: () => {
58        }
59      },
60    })
61  }
62
63  routeToNextInstallCert(fileUri: string): void {
64    FileIoModel.getMediaFileSuffix(fileUri, (suffix: string | undefined) => {
65      if (suffix !== undefined) {
66        console.debug(TAG, 'suffix = ', suffix);
67        if ((suffix === 'cer') || (suffix === 'pem')) {
68          CmInstallPresenter.getInstance().installCert(fileUri, '', suffix, true);
69        } else {
70          this.unrecognizedFileTips();
71        }
72      }
73    })
74  }
75
76  routeToNextInstallEvidence(fileUri: string): void {
77    FileIoModel.getMediaFileSuffix(fileUri, (suffix: string | undefined) => {
78      if (suffix !== undefined) {
79        console.debug(TAG, 'suffix = ', suffix);
80        if ((suffix === 'p12') || (suffix === 'pfx')) {
81          let fileInfo = new RouterFileVo(fileUri, suffix);
82          router.pushUrl({
83            url: 'pages/certPwdInput',
84            params: fileInfo
85          })
86        } else {
87          this.unrecognizedFileTips();
88        }
89      }
90    })
91  }
92
93  startInstallCert(context: Context): void {
94    if (context === undefined || context === null) {
95      console.error(TAG + 'startInstallCert, context is undefined');
96      return;
97    }
98    try {
99      let documentSelectOptions = new picker.DocumentSelectOptions();
100      let documentPicker = new picker.DocumentViewPicker(context);
101      console.info(TAG + 'start documentPicker.select');
102      documentPicker.select(documentSelectOptions).then((documentSelectResult) => {
103        if (documentSelectResult.length >= 1) {
104          this.routeToNextInstallCert(String(documentSelectResult[0]))
105        } else {
106          console.error(TAG + 'documentPicker.select length invalid:' + documentSelectResult.length);
107        }
108      }).catch((err: BusinessError) => {
109        console.error(TAG + 'documentPicker.select failed with err, message: ' + err.message + ', code: ' + err.code);
110      });
111    } catch (err) {
112      let e: BusinessError = err as BusinessError;
113      console.error(TAG + 'DocumentViewPicker failed with err, message: ' + e.message + ', code: ' + e.code);
114    }
115  }
116
117  startInstallEvidence(context: Context): void {
118    if (context === undefined || context === null) {
119      console.error(TAG + 'startInstallEvidence, context is undefined');
120      return;
121    }
122    try {
123      let documentSelectOptions = new picker.DocumentSelectOptions();
124      let documentPicker = new picker.DocumentViewPicker(context);
125      console.info(TAG + 'start documentPicker.select');
126      documentPicker.select(documentSelectOptions).then((documentSelectResult) => {
127        if (documentSelectResult.length >= 1) {
128          this.routeToNextInstallEvidence(String(documentSelectResult[0]))
129        } else {
130          console.error(TAG + 'documentPicker.select length invalid:' + documentSelectResult.length);
131        }
132      }).catch((err: BusinessError) => {
133        console.error(TAG + 'documentPicker.select failed with err, message: ' + err.message + ', code: ' + err.code);
134      });
135    } catch (err) {
136      let e: BusinessError = err as BusinessError;
137      console.error(TAG + 'DocumentViewPicker failed with err, message: ' + e.message + ', code: ' + e.code);
138    }
139  }
140
141  startRequestAuth(uri: string): void {
142    let appUidInfo = new RouterAppUidVo(uri);
143    router.pushUrl({
144      url: 'pages/requestAuth',
145      params: appUidInfo
146    });
147  }
148
149  uninstallAllCert(): void {
150    certManagerModel.delAllCertOrCred(CMModelOptType.CM_MODEL_OPT_USER_CA, (errCode: CMModelErrorCode) => {
151      if (errCode === CMModelErrorCode.CM_MODEL_ERROR_SUCCESS) {
152        console.info(TAG + 'uninstallAllCert CM_MODEL_OPT_USER_CA success');
153      } else {
154        console.error(TAG + 'uninstallAllCert CM_MODEL_OPT_USER_CA failed');
155      }
156    });
157
158    certManagerModel.delAllCertOrCred(CMModelOptType.CM_MODEL_OPT_APP_CRED, (errCode: CMModelErrorCode) => {
159      if (errCode === CMModelErrorCode.CM_MODEL_ERROR_SUCCESS) {
160        console.info(TAG + 'uninstallAllCert CM_MODEL_OPT_APP_CRED success');
161      } else {
162        console.error(TAG + 'uninstallAllCert CM_MODEL_OPT_APP_CRED failed');
163      }
164    });
165  }
166
167  startInstall(installType: string, fileUri: string) {
168    if (installType === 'CACert') {
169      let titleStr = getContext().resourceManager.getStringSync($r('app.string.Identity_Authentication'));
170      checkUserAuthModel.auth(titleStr, (authResult: boolean) => {
171        if (authResult) {
172          console.info('checkUserAuth success');
173          this.routeToNextInstallCert(fileUri);
174        }
175      })
176    } else if (installType === 'userCred') {
177      AppStorage.setOrCreate('installSystemCred', false);
178      AppStorage.setOrCreate('installUserCred', true);
179      this.routeToNextInstallEvidence(fileUri);
180    } else if (installType === 'systemCred') {
181      AppStorage.setOrCreate('installSystemCred', true);
182      AppStorage.setOrCreate('installUserCred', false);
183      this.routeToNextInstallEvidence(fileUri);
184    } else {
185      console.error(TAG, 'The installType is not supported');
186    }
187  }
188}