• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
16import notification from '@ohos.notification'
17import prompt from '@ohos.prompt'
18import reminderAgent from '@ohos.reminderAgentManager';
19import vibrator from '@ohos.vibrator'
20import AudioPlayer from './AudioPlayer'
21import Constant from '../common/Constant'
22import Logger from './Logger'
23import PreferencesDataManager from './PreferencesDataManager'
24import { Reminder } from '../common/Reminder'
25import TimeConversion from './TimeConversion'
26
27const TAG: string = 'AlarmClockReminder'
28
29class AlarmClockReminder {
30  public alarmClockReminders: Reminder[] = []
31
32  async setAlarmReminder(time: TimePickerResult) {
33    let hour = time.hour < 10 ? `0${time.hour}` : time.hour
34    let minute = time.minute < 10 ? `0${time.minute}` : time.minute
35    let context: any = getContext(this)
36    let selectTime: string = `${hour}:${minute}`
37    let isExistName = this.alarmClockReminders.find(element => element.reminderName === selectTime) !== undefined
38    if (!isExistName) {
39      let reminder: Reminder = {
40        audioSrc: '',
41        audioTimeouts: 0,
42        isStart: false,
43        isVibrator: false,
44        reminderId: 0,
45        reminderName: '',
46        vibratorTimeouts: 0,
47        reminderRequestAlarm: undefined
48      }
49      await reminderAgent.addNotificationSlot({ type: notification.SlotType.CONTENT_INFORMATION })
50      reminder.reminderName = selectTime
51      let alarm: reminderAgent.ReminderRequestAlarm = {
52        reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM,
53        hour: time.hour,
54        minute: time.minute,
55        actionButton:
56        [
57          {
58            title: context.resourceManager.getStringSync($r('app.string.alarm_clock_close').id),
59            type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE
60          },
61          {
62            title: context.resourceManager.getStringSync($r('app.string.alarm_clock_postpone').id),
63            type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE
64          }
65        ],
66        slotType: notification.SlotType.CONTENT_INFORMATION,
67        ringDuration: Constant.REMINDER_DURATION,
68        wantAgent: { pkgName: 'ohos.samples.reminderagentmanager', abilityName: 'MainAbility' },
69        title: context.resourceManager.getStringSync($r('app.string.alarm_clock').id),
70        content: context.resourceManager.getStringSync($r('app.string.alarm_clock_reach').id),
71        snoozeTimes: 0,
72        timeInterval: 0,
73        daysOfWeek: []
74      }
75      Logger.info(TAG, `this alarm clock is ${JSON.stringify(alarm)}`)
76      reminder.reminderRequestAlarm = alarm
77      reminder.isStart = false
78      this.alarmClockReminders.push(reminder)
79      Logger.info(TAG, `setAlarmReminder this all alarmclock is ${JSON.stringify(this.alarmClockReminders)}`)
80      await PreferencesDataManager.putData('alarmClock', this.alarmClockReminders)
81    } else {
82      prompt.showToast({
83        message: context.resourceManager.getStringSync($r('app.string.alarm_clock_existence').id),
84        duration: Constant.PROMPT_DURATION
85      })
86    }
87  }
88
89  async setToggle(isOn: boolean, index: number) {
90    this.alarmClockReminders[index].isStart = isOn
91    if (isOn) {
92      await reminderAgent.addNotificationSlot({ type: notification.SlotType.SOCIAL_COMMUNICATION })
93      let reminderId = await reminderAgent.publishReminder(this.alarmClockReminders[index].reminderRequestAlarm)
94      this.alarmClockReminders[index].reminderId = reminderId
95      if (this.alarmClockReminders[index].audioSrc) {
96        let audioIndex: number = await AudioPlayer.getAudioID(this.alarmClockReminders[index].audioSrc,
97          TimeConversion.timeToMillisecond(this.alarmClockReminders[index].reminderRequestAlarm.hour,
98          this.alarmClockReminders[index].reminderRequestAlarm.minute) * Constant.SECONDS_MILLISECONDS)
99        this.alarmClockReminders[index].audioTimeouts = audioIndex
100      }
101      await PreferencesDataManager.putData('alarmClock', this.alarmClockReminders)
102      if (this.alarmClockReminders[index].isVibrator) {
103        let vibratorId = setTimeout(function () {
104          vibrator.vibrate(Constant.VIBRATOR_DURATION, function (err) {
105            if (err) {
106              Logger.error(TAG, `setToggle this vibrator is failed err is ${JSON.stringify(err)}`)
107            }
108          })
109        }, TimeConversion.timeToMillisecond(this.alarmClockReminders[index].reminderRequestAlarm.hour,
110        this.alarmClockReminders[index].reminderRequestAlarm.minute) * Constant.SECONDS_MILLISECONDS)
111        this.alarmClockReminders[index].vibratorTimeouts = vibratorId
112        Logger.info(TAG, `setToggle this all alarmclock is ${JSON.stringify(this.alarmClockReminders)}`)
113        await PreferencesDataManager.putData('alarmClock', this.alarmClockReminders)
114      } else {
115        clearTimeout(this.alarmClockReminders[index].vibratorTimeouts)
116        await vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME)
117      }
118    } else {
119      clearTimeout(this.alarmClockReminders[index].vibratorTimeouts)
120      clearTimeout(this.alarmClockReminders[index].audioTimeouts)
121      await PreferencesDataManager.putData('alarmClock', this.alarmClockReminders)
122      await reminderAgent.cancelReminder(this.alarmClockReminders[index].reminderId)
123      await vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME)
124    }
125  }
126
127  async openDialog(dialog: CustomDialogController, index: number) {
128    try {
129      await reminderAgent.cancelReminder(this.alarmClockReminders[index].reminderId)
130    } catch (err) {
131      Logger.error(TAG, `openDialog this cancelReminder is not exist,err is ${JSON.stringify(err)}`)
132    }
133    dialog.open()
134  }
135
136  async deleteAlarmReminder(index: number) {
137    try {
138      clearTimeout(this.alarmClockReminders[index].vibratorTimeouts)
139      clearTimeout(this.alarmClockReminders[index].audioTimeouts)
140      reminderAgent.cancelReminder(this.alarmClockReminders[index].reminderId).then(() => {
141        Logger.info(TAG, `deleteAlarmReminder cancelReminder is succeed`)
142      }).catch((err) => {
143        Logger.info(TAG, `deleteAlarmReminder cancelReminder is not exist err is ${JSON.stringify(err)}`)
144      })
145      vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME).then(() => {
146        Logger.info(TAG, `deleteAlarmReminder stop vibrator is succeed`)
147      }).catch((err) => {
148        Logger.error(TAG, `deleteAlarmReminder vibrator is not exist err is ${JSON.stringify(err)}`)
149      })
150      this.alarmClockReminders[index].isStart = false
151      this.alarmClockReminders[index].reminderName = ''
152      this.alarmClockReminders[index].vibratorTimeouts = 0
153      this.alarmClockReminders[index].reminderRequestAlarm = undefined
154    } catch (err) {
155      Logger.info(TAG, `this cancel not exist err is ${JSON.stringify(err)}`)
156    }
157    this.alarmClockReminders.splice(index, 1)
158    Logger.info(TAG, `deleteAlarmReminder this all alarmclock is ${JSON.stringify(this.alarmClockReminders)}`)
159    PreferencesDataManager.putData('alarmClock', this.alarmClockReminders).then(() => {
160      Logger.info(TAG, `deleteAlarmReminder this put data is successed`)
161    })
162  }
163}
164
165export default new AlarmClockReminder()