1/**
2 * Copyright (c) 2022 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
16/**
17 * @file: notification manager
18 */
19
20import wantAgent from '@ohos.wantAgent';
21import notification from '@ohos.notification';
22import commonEvent from '@ohos.commonEvent';
23import callStateConst from '../common/constant/CallStateConst';
24import LogUtils from '../common/utils/LogUtils';
25import * as Constants from '../common/utils/Constants';
26
27const TAG = 'NotificationManager';
28const ID = 0;
29
30const notificationRequest = {
31  content: {
32    contentType: notification.ContentType.NOTIFICATION_CONTENT_LONG_TEXT,
33    longText: {
34      title: '',
35      text: '',
36      longText: '',
37      briefText: '',
38      expandedTitle: ''
39    }
40  },
41  id: ID,
42  wantAgent: null,
43  actionButtons: [],
44  slotType: notification.SlotType.OTHER_TYPES,
45  deliveryTime: new Date().getTime()
46};
47
48const textMap =
49  {
50    'answer': $r('app.string.answer'),
51    'reject': $r('app.string.reject'),
52    'hangUp': $r('app.string.hangUp'),
53    'mute': $r('app.string.mute'),
54    'callHold': $r('app.string.callHold'),
55  };
56
57export default class NotificationManager {
58  /**
59   * Send notification
60   *
61   * @param { Object } text - text info
62   *
63   * @param { Object } callData - call data
64   *
65   * @param { FUnction } $t - i18n format
66   */
67  async sendNotification(callData) {
68    const {callState, accountNumber, contactName, callId} = callData;
69    const actionBtnKeys = this.getMapObj(callState) || [];
70    const {START_ABILITY, SEND_COMMON_EVENT} = wantAgent.OperationType;
71    const wantAgentObj = await this.getWantAgent(callData, START_ABILITY);
72    let titleName = ' ';
73    let expandedName = ' ';
74    if (contactName) {
75      titleName = contactName;
76      expandedName = accountNumber;
77    } else {
78      titleName = accountNumber;
79      expandedName = ' ';
80    }
81    notificationRequest.wantAgent = wantAgentObj;
82    notificationRequest.actionButtons = [];
83
84    if (actionBtnKeys.length) {
85      for (const key of actionBtnKeys) {
86        const data = {
87          callId, btnType: key
88        };
89        LogUtils.i(TAG, 'sendNotification getResourceManager key:' + JSON.stringify(key));
90        const wantAgentObj = await this.getWantAgent(data, SEND_COMMON_EVENT);
91        const title = globalThis.calluiAbilityContext?.resourceManager.getStringSync(textMap[key]);
92        LogUtils.i(TAG, 'sendNotification getResourceManager textMap[key].id:' + JSON.stringify(title));
93        notificationRequest.actionButtons.push({
94          title: title,
95          wantAgent: wantAgentObj
96        });
97        LogUtils.i(TAG, 'sendNotification getResourceManager notificationRequest.actionButtons.push:' + JSON.stringify(notificationRequest.actionButtons));
98      }
99    }
100    Object.assign(notificationRequest.content.longText, {
101      title: titleName,
102      text: expandedName,
103      expandedTitle: titleName,
104      longText: expandedName
105    });
106    notification.publish(notificationRequest).then((data) => {
107      LogUtils.i(TAG, 'sendNotification publish success')
108    }).catch((err) => {
109      LogUtils.i(TAG, 'sendNotification public err' + JSON.stringify(err))
110    });
111    LogUtils.i(TAG, 'sendNotification end :')
112  }
113
114  /**
115   * Get call status
116   * @param callState
117   */
118  getMapObj(callState) {
119    if (callState === callStateConst.CALL_STATUS_INCOMING) {
120      return ['answer', 'reject']
121    }
122    if (callState === callStateConst.CALL_STATUS_ACTIVE) {
123      return ['hangUp']
124    }
125    if (callState === callStateConst.CALL_STATUS_HOLDING) {
126      return ['hangUp']
127    }
128    if (callState === callStateConst.CALL_STATUS_ALERTING) {
129      return ['hangUp']
130    }
131    if (callState === callStateConst.CALL_STATUS_DIALING) {
132      return ['hangUp']
133    }
134    if (callState === callStateConst.CALL_STATUS_WAITING) {
135      return ['answer', 'reject']
136    }
137  }
138
139  /**
140   * get want agent
141   *
142   * @param { object } data - call data
143   *
144   * @param { number } operationType - type
145   */
146  getWantAgent(data, operationTypes) {
147    if (!wantAgent) {
148      LogUtils.i(TAG, 'wantAgent is not exist');
149      return;
150    }
151    return wantAgent.getWantAgent({
152      wants: [{
153                deviceId: '',
154                bundleName: Constants.CALL_BUNDLE_NAME,
155                abilityName: Constants.CALL_ABILITY_NAME,
156                uri: '',
157                type: 'phone',
158                action: 'callui.event.click',
159                parameters: data,
160                entities: []
161              }],
162      requestCode: 0,
163      operationType: operationTypes,
164      wantAgentFlags: [wantAgent.WantAgentFlags.ONE_TIME_FLAG]
165    });
166  }
167
168  /**
169   * Cancel notice
170   */
171  cancelNotification() {
172    LogUtils.i(TAG, 'cancelNotification')
173    notification.cancel(ID).then((res) => {
174      LogUtils.i(TAG, 'notify.cancel res data : %s' + JSON.stringify(res))
175    }).catch((err) => {
176      LogUtils.i(TAG, 'notify.cancel err data : %s' + JSON.stringify(err))
177    });
178  }
179
180  /**
181   * send capsule notification
182   *
183   * @param {Object} callData - call data
184   *
185   * @param {boolean} isBackground - is background
186   */
187  sendCapsuleNotification(callData, isBackground) {
188    LogUtils.i(TAG, 'sendCapsuleNotification isBackground : ' + JSON.stringify(isBackground))
189    LogUtils.i(TAG, 'sendCapsuleNotification callData.startTime :')
190    const {callState, startTime} = callData;
191    let commonEventPublishData = {
192      bundleName: 'com.ohos.systemui',
193      isOrdered: false,
194      subscriberPermissions: ['ohos.permission.GET_TELEPHONY_STATE'],
195      data: JSON.stringify({
196        callState,
197        startTime: startTime * 1000,
198        isBackground,
199        wantBundleName: Constants.CALL_BUNDLE_NAME,
200        wantAbilityName: Constants.CALL_ABILITY_NAME
201      })
202    }
203
204    commonEvent.publish('CAPSULE_EVENT_CALL_UI', commonEventPublishData, (err, data) => {
205      if (err) {
206        LogUtils.i(TAG, 'sendCapsuleNotification publish launcher err:' + JSON.stringify(err))
207      } else {
208        LogUtils.i(TAG, 'sendCapsuleNotification publish launcher success:' + JSON.stringify(data))
209      }
210    })
211  }
212}