2020-10-14 12:56:27 +01:00
import Logger from 'lib/Logger' ;
2020-10-09 18:35:46 +01:00
import { Notification } from 'lib/models/Alarm' ;
2020-10-14 12:56:27 +01:00
const ReactNativeAN = require ( 'react-native-alarm-notification' ) . default ;
2017-11-27 22:50:46 +00:00
2020-10-09 18:35:46 +01:00
export default class AlarmServiceDriver {
2020-10-14 12:56:27 +01:00
private logger_ :Logger ;
2019-01-10 18:49:26 +00:00
2020-10-14 12:56:27 +01:00
constructor ( logger :Logger ) {
this . logger_ = logger ;
2018-12-20 14:52:56 +01:00
}
2020-10-14 12:56:27 +01:00
public hasPersistentNotifications() {
2017-11-28 00:22:38 +00:00
return true ;
}
2020-10-14 12:56:27 +01:00
public notificationIsSet() {
2019-07-29 15:43:53 +02:00
throw new Error ( 'Available only for non-persistent alarms' ) ;
2017-11-28 00:22:38 +00:00
}
2020-10-14 12:56:27 +01:00
public async clearNotification ( id :number ) {
const alarm = await this . alarmByJoplinNotificationId ( id ) ;
if ( ! alarm ) return ;
this . logger_ . info ( 'AlarmServiceDriver: Deleting alarm:' , alarm ) ;
await ReactNativeAN . deleteAlarm ( alarm . id ) ;
}
// Returns -1 if could not be found
private alarmJoplinAlarmId ( alarm :any ) : number {
if ( ! alarm . data ) return - 1 ;
const m = alarm . data . match ( /joplinNotificationId==>(\d+)/ )
return m ? Number ( m [ 1 ] ) : - 1 ;
2017-11-27 22:50:46 +00:00
}
2019-07-29 15:43:53 +02:00
2020-10-14 12:56:27 +01:00
private async alarmByJoplinNotificationId ( joplinNotificationId :number ) {
const alarms :any [ ] = await ReactNativeAN . getScheduledAlarms ( ) ;
for ( const alarm of alarms ) {
const id = this . alarmJoplinAlarmId ( alarm ) ;
if ( id === joplinNotificationId ) return alarm ;
}
this . logger_ . warn ( 'AlarmServiceDriver: Could not find alarm that matches Joplin notification ID. It could be because it has already been triggered:' , joplinNotificationId ) ;
return null ;
}
public async scheduleNotification ( notification :Notification ) {
const alarmNotifData = {
title : notification.title ,
message : notification.body ? notification . body : '-' , // Required
channel : "net.cozic.joplin.notification" ,
small_icon : "ic_launcher" ,
color : 'white' ,
data : { joplinNotificationId : notification.id + '' } ,
2019-01-10 18:49:26 +00:00
} ;
2020-10-14 12:56:27 +01:00
// ReactNativeAN expects a string as a date and it seems this utility
// function converts it to the right format.
const fireDate = ReactNativeAN . parseDate ( notification . date ) ;
const alarm = await ReactNativeAN . scheduleAlarm ( { . . . alarmNotifData , fire_date : fireDate } ) ;
this . logger_ . info ( 'AlarmServiceDriver: Created new alarm:' , alarm ) ;
2017-11-27 22:50:46 +00:00
}
}