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 { BusinessError } from '@ohos.base';
17import display from '@ohos.display';
18import StartOptions from '@ohos.app.ability.StartOptions';
19import common from '@ohos.app.ability.common';
20import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession';
21import osAccount from '@ohos.account.osAccount';
22import account_osAccount from '@ohos.account.osAccount';
23import Constants from './constant';
24import GlobalContext from './GlobalContext';
25import deviceInfo from '@ohos.deviceInfo';
26import promptAction from '@ohos.promptAction';
27import { HiLog } from '../common/HiLog';
28import AccountManager from '../manager/AccountManager';
29import CommonUtil from './CommonUtil';
30
31const TAG = 'AlertMessage';
32
33export class GetAlertMessage {
34
35  public static async startAlertAbility(
36    context: common.UIAbilityContext | common.ServiceExtensionContext | common.UIExtensionContext,
37    error: BusinessError,
38    session?: UIExtensionContentSession
39  ) {
40    if (deviceInfo.deviceType !== '2in1') {
41      GetAlertMessage.phoneHandle(context, error);
42      return;
43    }
44    let dis = display.getDefaultDisplaySync();
45    let xNumber = Math.floor(
46      (dis.width - Constants.START_ABILITY_CUSTOM_CONTENT_DIALOG_WIDTH) * Constants.RATIO_HALF
47    );
48    let yNumber = Math.floor(
49      (dis.height - Constants.START_ABILITY_CUSTOM_CONTENT_DIALOG_HEIGHT) * Constants.RATIO_HALF
50    );
51    let options: StartOptions = {
52      withAnimation: true,
53      windowLeft: xNumber,
54      windowTop: yNumber,
55      windowWidth: Constants.START_ABILITY_CUSTOM_CONTENT_DIALOG_WIDTH,
56      windowHeight: Constants.START_ABILITY_CUSTOM_CONTENT_DIALOG_HEIGHT
57    };
58    HiLog.info(TAG, `set options: ${JSON.stringify(options)}`);
59    context.startAbility({
60      bundleName: Constants.DLP_MANAGER_BUNDLE_NAME,
61      abilityName: 'AlertAbility',
62      parameters: {
63        error: error,
64        accountType: GlobalContext.load('accountType')
65      }
66    }, options, async (err: BusinessError) => {
67      if (err && err.code !== 0) {
68        HiLog.error(TAG, `start AlertAbility failed: ${JSON.stringify(err)}`);
69      }
70      if (session) {
71        session.terminateSelfWithResult({
72          'resultCode': 0,
73          'want': {
74            'bundleName': Constants.DLP_MANAGER_BUNDLE_NAME,
75          },
76        });
77      } else {
78        context.terminateSelf();
79      }
80    })
81  }
82
83  public static async phoneHandle(
84    context: common.UIAbilityContext | common.ServiceExtensionContext | common.UIExtensionContext,
85    error: BusinessError
86  ) {
87    try {
88      let resource = GetAlertMessage.getToastMessage(error);
89      let toastMessage = await context.resourceManager.getStringValue(resource);
90      promptAction.showToast({
91        message: toastMessage,
92        duration: Constants.SHARE_SET_TIMEOUT
93      });
94      HiLog.info(TAG, 'showToast end.');
95    } catch (error) {
96      HiLog.error(TAG, `showToast error: ${JSON.stringify(error)}`);
97    } finally {
98      setTimeout(() => {
99        context.terminateSelf();
100      }, Constants.SHARE_SET_TIMEOUT);
101    }
102  }
103
104  public static getAlertMessage(err: BusinessError, defaultTitle?: Resource, defaultMessage?: Resource) {
105    switch (err && err.code) {
106      case Constants.ERR_JS_ACCOUNT_NOT_FOUND:
107      case Constants.ERR_JS_GET_ACCOUNT_ERROR:
108        return { 'msg': $r('app.string.MESSAGE_APP_GET_ACCOUNT_ERROR') } as Record<string, Resource>;
109      case Constants.ERR_JS_APP_NO_ACCOUNT_ERROR:
110      case Constants.ERR_JS_ACCOUNT_NOT_LOGIN:
111        return { 'msg': $r('app.string.MESSAGE_APP_NO_ACCOUNT_ERROR') } as Record<string, Resource>;
112      case Constants.ERR_JS_APP_GET_FILE_ASSET_ERROR:
113        return { 'msg': $r('app.string.MESSAGE_APP_GET_FILE_ASSET_ERROR') } as Record<string, Resource>;
114      case Constants.ERR_JS_RELEASE_FILE_OPEN:
115      case Constants.ERR_JS_NOT_AUTHORIZED_APPLICATION:
116        return { 'msg': $r('app.string.MESSAGE_NOT_AUTHORIZED_APPLICATION') } as Record<string, Resource>;
117      case Constants.ERR_JS_NETWORK_INVALID:
118      case Constants.ERR_JS_APP_NETWORK_INVALID:
119        return { 'msg': $r('app.string.network_invalid') } as Record<string, Resource>;
120      case Constants.ERR_JS_CREDENTIAL_SERVICE_ERROR:
121      case Constants.ERR_JS_CREDENTIAL_SERVER_ERROR:
122      case Constants.ERR_JS_CREDENTIAL_TIMEOUT:
123      case Constants.ERR_JS_APP_INSIDE_ERROR:
124        return { 'msg': $r('app.string.MESSAGE_SERVICE_INSIDE_ERROR') } as Record<string, Resource>;
125      case Constants.ERR_JS_NOT_DLP_FILE:
126        return { 'msg': $r('app.string.MESSAGE_APP_FILE_PARAM_ERROR') } as Record<string, Resource>;
127      case Constants.ERR_JS_USER_NO_PERMISSION:
128        return { 'msg': $r('app.string.MESSAGE_APP_NOT_HAVE_PERM') } as Record<string, Resource>;
129      case Constants.ERR_JS_OTHER_APP_OPEN_FILE:
130        return { 'msg': $r('app.string.This_File_is_Open_By_Other_App') } as Record<string, Resource>;
131      case Constants.ERR_JS_OFFLINE:
132        return { 'msg': $r('app.string.network_invalid') } as Record<string, Resource>;
133      default:
134        if (defaultTitle !== undefined && defaultMessage != undefined) {
135          return { 'title': defaultTitle, 'msg': defaultMessage } as Record<string, Resource>;
136        } else {
137          return { 'msg': $r('app.string.MESSAGE_SERVICE_INSIDE_ERROR') } as Record<string, Resource>;
138        }
139    }
140  }
141
142  public static getAlertTitleMessage(err: BusinessError) {
143    switch (err && err.code) {
144      case Constants.ERR_JS_USER_NO_PERMISSION:
145        return {
146          'title': $r('app.string.TITLE_APP_VISIT_FILE_ERROR'),
147          'msg': $r('app.string.MESSAGE_APP_NOT_HAVE_PERM_VISIT', err.message.split(', contact:')?.[1])
148        } as Record<string, Resource>;
149      case Constants.ERR_JS_APP_PARAM_ERROR:
150        return {
151          'title': $r('app.string.TITLE_APP_ERROR'),
152          'msg': $r('app.string.MESSAGE_APP_PARAM_ERROR')
153        } as Record<string, Resource>;
154      case Constants.ERR_JS_APP_OPEN_REJECTED:
155        return {
156          'title': $r('app.string.header_title'),
157          'msg': $r('app.string.MESSAGE_DLP_OPEN_REJECT')
158        } as Record<string, Resource>;
159      case Constants.ERR_JS_APP_ENCRYPTION_REJECTED:
160        return {
161          'title': $r('app.string.header_title'),
162          'msg': $r('app.string.MESSAGE_DLP_ENCRYPTION_REJECTED')
163        } as Record<string, Resource>;
164      case Constants.ERR_JS_APP_ENCRYPTING:
165        return {
166          'title': $r('app.string.header_title'),
167          'msg': $r('app.string.MESSAGE_DLP_ENCRYPTION', err.data)
168        } as Record<string, Resource>;
169      case Constants.ERR_JS_FILE_EXPIRATION:
170        return {
171          'title': $r('app.string.Permission_has_expired'),
172          'msg': $r('app.string.Permission_has_expired_description', err.message.split(', contact:')?.[1])
173        } as Record<string, Resource>;
174      case Constants.ERR_JS_DLP_FILE_READ_ONLY:
175        return {
176          'title': $r('app.string.TITLE_APP_VISIT_FILE_ERROR'),
177          'msg': $r('app.string.MESSAGE_DLP_READ_ONLY', AppStorage.get('contactAccount'))
178        } as Record<string, Resource>;
179      case Constants.ERR_JS_SYSTEM_NEED_TO_BE_UPGRADED:
180        return {
181          'title': $r('app.string.TITLE_APP_VERSION_LOWER'),
182          'msg': $r('app.string.MESSAGE_DLP_SYSTEM_NEED_TO_BE_UPGRADED')
183        } as Record<string, Resource>;
184      default:
185        return {
186          'title': $r('app.string.header_title'),
187          'msg': $r('app.string.MESSAGE_SERVICE_INSIDE_ERROR')
188        } as Record<string, Resource>;
189    }
190  }
191
192  public static getAlertButtonMessage(err: BusinessError) {
193    switch (err && err.code) {
194      case Constants.ERR_JS_APP_SYSTEM_IS_AUTHENTICATED:
195        return {
196          'title': $r('app.string.header_title'),
197          'msg': $r('app.string.MESSAGE_DLP_SYSTEM_IS_AUTHENTICATED'),
198          'cancel': $r('app.string.ban'),
199          'ok': $r('app.string.SYSTEM_IS_AUTHENTICATED_LOGIN')
200        } as Record<string, Resource>;
201      default:
202        return {
203          'title': $r('app.string.header_title'),
204          'msg': $r('app.string.MESSAGE_SERVICE_INSIDE_ERROR')
205        } as Record<string, Resource>;
206    }
207  }
208
209  public static getToastMessage(err: BusinessError) {
210    switch (err && err.code) {
211      case Constants.ERR_JS_APP_GET_FILE_ASSET_ERROR:
212        return $r('app.string.MESSAGE_APP_GET_FILE_ASSET_ERROR');
213      case Constants.ERR_JS_NETWORK_INVALID:
214      case Constants.ERR_JS_APP_NETWORK_INVALID:
215      case Constants.ERR_JS_OFFLINE:
216        return $r('app.string.network_invalid');
217      case Constants.ERR_JS_NOT_DLP_FILE:
218        return $r('app.string.MESSAGE_APP_FILE_PARAM_ERROR');
219      case Constants.ERR_JS_USER_NO_PERMISSION:
220        return $r('app.string.MESSAGE_APP_NOT_HAVE_PERM');
221      case Constants.ERR_JS_SYSTEM_NEED_TO_BE_UPGRADED:
222        return $r('app.string.MESSAGE_DLP_SYSTEM_NEED_TO_BE_UPGRADED');
223      case Constants.ERR_JS_APP_CANNOT_OPEN:
224        return $r('app.string.THIS_FILE_NOT_SUPPORT_ENCRYPTION_PROTECTION');
225      case Constants.ERR_JS_OTHER_APP_OPEN_FILE:
226        return $r('app.string.This_File_is_Open_By_Other_App');
227      default:
228        return $r('app.string.MESSAGE_SERVICE_INSIDE_ERROR');
229    }
230  }
231
232  public static async checkAccountInfo(accountName: string): Promise<boolean> {
233
234    let domainAccount = await AccountManager.getDomainAccountByAccountName(accountName);
235    return !CommonUtil.isEmptyStr(domainAccount.accountName);
236  }
237
238  public static async requestModalUIExtension(
239    context: common.UIAbilityContext | common.ServiceExtensionContext, error: BusinessError
240  ){
241    if (deviceInfo.deviceType !== '2in1') {
242      GetAlertMessage.phoneHandle(context, error);
243      return;
244    };
245    let uiExtWant: Want = {
246      bundleName: Constants.DLP_MANAGER_BUNDLE_NAME,
247      abilityName: 'DialogUIExtAbility',
248      moduleName: 'entry',
249      parameters: {
250        'bundleName': AppStorage.get('paramCallerBundleName') ?? '',
251        'ability.want.params.uiExtensionType': 'sys/commonUI',
252        'error': error,
253        'accountType': GlobalContext.load('accountType')
254      }
255    };
256    try {
257      context.requestModalUIExtension(uiExtWant)
258        .then(() => {
259          HiLog.info(TAG, 'requestModalUIExtension succeed');
260        })
261        .catch((err: BusinessError) => {
262          HiLog.error(TAG, `requestModalUIExtension failed. Cause: ${JSON.stringify(err)}`);
263        })
264    } catch (err) {
265      let code = (err as BusinessError).code;
266      let message = (err as BusinessError).message;
267      HiLog.error(TAG, `requestModalUIExtension failed. Cause: ${JSON.stringify(err)}`);
268    }
269  }
270}