class NotificationHandler { constructor(options) { this.options = options; } clearAll() { // clear notification count document.getElementById('notif-count').innerHTML = ''; // remove notifications document.getElementById('notif-body').innerHTML = ''; } loadAll() { console.log('loading notifications'); // ajax load var self = this; var notif_update_url = this.options['notif_ajax_update_url']; var xhr = new XMLHttpRequest(); xhr.open('GET', this.options['notif_ajax_url']); xhr.onload = function() { if (xhr.status === 200) { var data = JSON.parse(xhr.responseText); var notifs = data.notifications; // update notification unread count var count_html = data.unread_count; document.getElementById('notif-count').innerHTML = count_html; // do we have any notifications? if (notifs.length <= 0) return; // add actual notifications var notif_body = document.getElementById('notif-body'); var notif_index = 0; notifs.forEach(function(notif) { var notif_date = moment(notif.date).fromNow(); var notif_html = '
'; notif_html += ''; notif_html += ''; notif_html += '' + notif.text + '' notif_html += ''; notif_html += ''; notif_html += notif_date; notif_html += ''; notif_html += '
'; notif_body.insertAdjacentHTML('beforeend', notif_html); document.getElementsByClassName('m-list-timeline__item')[notif_index].addEventListener('click', function(e) { e.preventDefault(); $.ajax({ method: "POST", url: notif_update_url, data: {id: notif.id} }).done(function(response) { window.location.href = notif.link; }); }); notif_index++; }); } }; xhr.send(); } listen(user_id, host, port, use_ssl = false) { var d = new Date(); var client_id = "dash-" + user_id + "-" + d.getMonth() + "-" + d.getDate() + "-" + d.getHours() + "-" + d.getMinutes() + "-" + d.getSeconds() + "-" + d.getMilliseconds(); this.mqtt = new Paho.MQTT.Client(host, port, client_id); var options = { useSSL: use_ssl, timeout: 3, invocationContext: this, onSuccess: this.onConnect.bind(this) } this.mqtt.onMessageArrived = this.onMessage.bind(this); this.mqtt.connect(options); } onConnect(icontext) { console.log('notification mqtt connected'); var my = icontext.invocationContext; // subscribe to general notifications my.mqtt.subscribe('user/0/notification'); } onMessage(msg) { console.log('notification event received'); // we don't care about messasge, we update this.clearAll(); this.loadAll(); } getIcon(type_id) { if (type_id in this.options['icons']) { return this.options['icons'][type_id]; } return this.options['default_icon']; } }