2021-01-22 19:41:11 +02:00
import BaseModel from '../BaseModel' ;
2021-01-23 17:51:19 +02:00
import Note from './Note' ;
2017-11-28 00:50:46 +02:00
2020-10-09 19:35:46 +02:00
export interface Notification {
2020-11-12 21:29:22 +02:00
id : number ;
noteId : string ;
date : Date ;
title : string ;
body? : string ;
2020-10-09 19:35:46 +02:00
}
export default class Alarm extends BaseModel {
2023-03-06 16:22:01 +02:00
public static tableName() {
2017-11-28 00:50:46 +02:00
return 'alarms' ;
}
2023-03-06 16:22:01 +02:00
public static modelType() {
2017-11-28 00:50:46 +02:00
return BaseModel . TYPE_ALARM ;
}
2023-03-06 16:22:01 +02:00
public static byNoteId ( noteId : string ) {
2017-11-28 00:50:46 +02:00
return this . modelSelectOne ( 'SELECT * FROM alarms WHERE note_id = ?' , [ noteId ] ) ;
}
2023-03-06 16:22:01 +02:00
public static async deleteExpiredAlarms() {
2017-11-28 02:22:38 +02:00
return this . db ( ) . exec ( 'DELETE FROM alarms WHERE trigger_time <= ?' , [ Date . now ( ) ] ) ;
}
2017-11-28 00:50:46 +02:00
2023-03-06 16:22:01 +02:00
public static async alarmIdsWithoutNotes() {
2017-11-28 00:50:46 +02:00
// https://stackoverflow.com/a/4967229/561309
2017-11-28 02:22:38 +02:00
const alarms = await this . db ( ) . selectAll ( 'SELECT alarms.id FROM alarms LEFT JOIN notes ON alarms.note_id = notes.id WHERE notes.id IS NULL' ) ;
2020-11-12 21:13:28 +02:00
return alarms . map ( ( a : any ) = > {
2019-07-29 15:43:53 +02:00
return a . id ;
} ) ;
2017-11-28 00:50:46 +02:00
}
2023-03-06 16:22:01 +02:00
public static async makeNotification ( alarm : any , note : any = null ) : Promise < Notification > {
2018-12-08 01:42:29 +02:00
if ( ! note ) {
note = await Note . load ( alarm . note_id ) ;
} else if ( ! note . todo_due ) {
this . logger ( ) . warn ( 'Trying to create notification for note with todo_due property - reloading note object in case we are dealing with a partial note' ) ;
note = await Note . load ( alarm . note_id ) ;
this . logger ( ) . warn ( 'Reloaded note:' , note ) ;
}
2017-11-28 22:17:34 +02:00
2020-11-12 21:13:28 +02:00
const output : Notification = {
2017-11-28 22:17:34 +02:00
id : alarm.id ,
2020-10-09 19:35:46 +02:00
noteId : alarm.note_id ,
2017-11-28 22:17:34 +02:00
date : new Date ( note . todo_due ) ,
2019-07-29 15:43:53 +02:00
title : note.title.substr ( 0 , 128 ) ,
2017-11-28 22:17:34 +02:00
} ;
2019-07-29 15:43:53 +02:00
if ( note . body ) output . body = note . body . substr ( 0 , 512 ) ;
2017-11-28 22:17:34 +02:00
2019-07-29 15:43:53 +02:00
return output ;
2017-11-28 22:17:34 +02:00
}
2023-03-06 16:22:01 +02:00
public static async allDue() {
2017-11-28 22:31:14 +02:00
return this . modelSelectAll ( 'SELECT * FROM alarms WHERE trigger_time >= ?' , [ Date . now ( ) ] ) ;
}
2017-11-28 00:50:46 +02:00
}