ComunicWeb/assets/js/components/notifications/service.js

90 lines
2.5 KiB
JavaScript
Raw Normal View History

2018-02-19 08:39:00 +00:00
/**
* Notifications service
*
* @author Pierre HUBERT
*/
ComunicWeb.components.notifications.service = {
/**
* Last known number of notifications
*/
2020-03-31 09:14:44 +00:00
last_total_count: -1,
count_unread_notifications: -1,
count_unread_conv: -1,
2018-02-19 08:39:00 +00:00
/**
* Init the service
*
* @param {HTMLElement} target The target that will receive
* the number of unread notifications
* @param {Bool} auto_hide Automatically hide the notifications
* number if there is not any new notification
* @param {HTMLElement} target_conversations Optionnal, defins the target
* for the number of conversations
2018-02-19 08:39:00 +00:00
*/
2020-03-31 09:14:44 +00:00
init: async function(target, auto_hide, target_conversations){
2020-03-31 09:38:09 +00:00
const processResponse = () => {
2020-03-31 09:14:44 +00:00
if(!target.isConnected || this.count_unread_notifications < 0 || this.count_unread_conv < 0)
return;
//Update the target
target.innerHTML = this.count_unread_notifications;
//If the number of notifications equals 0, hide the target if required
target.style.display = this.count_unread_conv == 0 && auto_hide ? "none" : "block";
//Update the number of conversations if possible too
if(target_conversations){
2018-02-19 08:39:00 +00:00
//Update the target
2020-03-31 09:14:44 +00:00
target_conversations.innerHTML = this.count_unread_conv;
2018-02-19 08:39:00 +00:00
//If the number of notifications equals 0, hide the target if required
2020-03-31 09:14:44 +00:00
target_conversations.style.display = this.count_unread_conv == 0 && auto_hide ? "none" : "block";
2020-03-31 09:14:44 +00:00
}
2018-02-19 08:39:00 +00:00
2020-03-31 09:14:44 +00:00
//Sum notification number
let total_number_notifs = this.count_unread_conv + this.count_unread_notifications;
//Update page title too
ComunicWeb.common.pageTitle.setNotificationsNumber(total_number_notifs);
//Play song if required
if(this.last_total_count != -1 && total_number_notifs > this.last_total_count)
ComunicWeb.components.notifications.song.play();
this.last_total_count = total_number_notifs;
}
// Initial load
try {
const response = await ComunicWeb.components.notifications.interface.asyncGetAllUnread(false);
this.count_unread_conv = response.conversations;
this.count_unread_notifications = response.notifications;
this.last_total_count = response.notifications + response.conversations;
processResponse();
} catch(e) {
console.error("Could not get the number of unread notifications!")
console.error(e);
}
2020-03-31 09:38:09 +00:00
// Register to events
document.addEventListener("newNumberNotifs", e => {
this.count_unread_notifications = e.detail;
processResponse();
});
document.addEventListener("newNumberUnreadConvs", e => {
this.count_unread_conv = e.detail;
processResponse();
});
2018-02-19 08:39:00 +00:00
},
}