Browse Source

Improved push notifications

master
Igor Zhukov 8 years ago
parent
commit
41bdb545a1
  1. 8
      app/js/lib/ng_utils.js
  2. 76
      app/js/lib/push_worker.js
  3. 1
      app/js/locales/en-us.json
  4. 18
      app/js/services.js

8
app/js/lib/ng_utils.js

@ -1989,6 +1989,8 @@ angular.module('izhukov.utils', [])
var started = false var started = false
var settings = {} var settings = {}
var isAliveTO var isAliveTO
var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1
var userVisibleOnly = isFirefox ? false : true
if (!('PushManager' in window) || if (!('PushManager' in window) ||
!('Notification' in window) || !('Notification' in window) ||
@ -2035,7 +2037,7 @@ angular.module('izhukov.utils', [])
return return
} }
navigator.serviceWorker.ready.then(function(reg) { navigator.serviceWorker.ready.then(function(reg) {
reg.pushManager.subscribe({userVisibleOnly: true}).then(function(subscription) { reg.pushManager.subscribe({userVisibleOnly: userVisibleOnly}).then(function(subscription) {
// The subscription was successful // The subscription was successful
isPushEnabled = true isPushEnabled = true
pushSubscriptionNotify('subscribe', subscription) pushSubscriptionNotify('subscribe', subscription)
@ -2045,6 +2047,10 @@ angular.module('izhukov.utils', [])
console.log('Permission for Notifications was denied') console.log('Permission for Notifications was denied')
} else { } else {
console.log('Unable to subscribe to push.', e) console.log('Unable to subscribe to push.', e)
if (!userVisibleOnly) {
userVisibleOnly = true
setTimeout(subscribe, 0)
}
} }
}) })
}) })

76
app/js/lib/push_worker.js

@ -8,6 +8,15 @@ var muteUntil = false
var baseUrl var baseUrl
var settings var settings
var lang = {} var lang = {}
var userInvisibleSupported = false
var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1
if (isFirefox) {
userInvisibleSupported = true
}
switch (location.hostname) { switch (location.hostname) {
case 'localhost': case 'localhost':
@ -25,19 +34,49 @@ self.addEventListener('push', function(event) {
var obj = event.data.json() var obj = event.data.json()
console.log('[SW] push', obj) console.log('[SW] push', obj)
var closeAll = obj.badge ? !fireNotification(obj, event) : true var checksPromise = new Promise(function (resolve, reject) {
if (!obj.badge) {
if (closeAll) { return reject()
}
var nowTime = +(new Date())
if (userInvisibleSupported &&
muteUntil &&
nowTime < muteUntil) {
console.log('Supress notification because mute for ', (muteUntil - nowTime) / 60000, 'min')
return reject()
}
if (lastAliveTime &&
nowTime - lastAliveTime < 60000) {
return clients.matchAll({type: 'window'}).then(function(clientList) {
if (clientList.length) {
console.log('Supress notification because some instance is alive')
return reject()
}
return resolve()
})
}
return resolve()
})
var notificationPromise = checksPromise.then(function () {
fireNotification(obj)
})
var closePromise = notificationPromise.catch(function () {
console.log('[SW] Closing all notifications on push') console.log('[SW] Closing all notifications on push')
if (userInvisibleSupported) {
return closeAllNotifications
}
var promise = self.registration.showNotification('Telegram').then(function () { var promise = self.registration.showNotification('Telegram').then(function () {
// return closeAllNotifications() // return closeAllNotifications()
setTimeout(closeAllNotifications, 100) setTimeout(closeAllNotifications, 100)
}).catch(function (error) { }).catch(function (error) {
console.error('Show notification error', error) console.error('Show notification error', error)
}) })
if ('waitUntil' in event) { })
event.waitUntil(promise)
} if ('waitUntil' in event) {
event.waitUntil(closePromise)
} }
}) })
@ -74,17 +113,7 @@ self.addEventListener('message', function(event) {
} }
}) })
function fireNotification(obj, event) { function fireNotification(obj) {
var nowTime = +(new Date())
if (nowTime - lastAliveTime < 60000) {
console.log('Supress notification because some instance is alive')
return false
}
if (muteUntil && nowTime < muteUntil) {
console.log('Supress notification because mute for ', (muteUntil - nowTime) / 60000, 'min')
return false
}
var title = obj.title || 'Telegram' var title = obj.title || 'Telegram'
var body = obj.description || '' var body = obj.description || ''
var icon = 'img/logo_share.png' var icon = 'img/logo_share.png'
@ -125,19 +154,14 @@ function fireNotification(obj, event) {
] ]
}) })
var finalPromise = notificationPromise.then(function (event) { return notificationPromise.then(function (event) {
if (event && event.notification) { if (event && event.notification) {
pushToNotifications(event.notification) pushToNotifications(event.notification)
} }
return Promise.resolve()
}).catch(function (error) { }).catch(function (error) {
console.error('Show notification promise', error) console.error('Show notification promise', error)
}) })
if ('waitUntil' in event) {
event.waitUntil(finalPromise)
}
return true
} }
@ -150,12 +174,10 @@ function pushToNotifications(notification) {
} }
function onCloseNotification(event) { function onCloseNotification(event) {
muteUntil = Math.max(muteUntil || 0, +(new Date()) + 600000) // 10 min
removeFromNotifications(event.notification) removeFromNotifications(event.notification)
} }
function removeFromNotifications(notification) { function removeFromNotifications(notification) {
console.warn('on close', notification)
var pos = notifications.indexOf(notification) var pos = notifications.indexOf(notification)
if (pos != -1) { if (pos != -1) {
notifications.splice(pos, 1) notifications.splice(pos, 1)
@ -196,7 +218,7 @@ self.addEventListener('notificationclick', function(event) {
notification.close() notification.close()
var action = event.action var action = event.action
if (action == 'mute1d') { if (action == 'mute1d' && userInvisibleSupported) {
console.log('[SW] mute for 1d') console.log('[SW] mute for 1d')
muteUntil = +(new Date()) + 86400000 muteUntil = +(new Date()) + 86400000
IDBManager.setItem('push_mute_until', muteUntil.toString()) IDBManager.setItem('push_mute_until', muteUntil.toString())

1
app/js/locales/en-us.json

@ -606,6 +606,7 @@
"push_action_mute1d_mobile": "Mute for 24H", "push_action_mute1d_mobile": "Mute for 24H",
"push_action_settings_mobile": "Alerts settings", "push_action_settings_mobile": "Alerts settings",
"push_message_nopreview": "You have a new message", "push_message_nopreview": "You have a new message",
"push_action_mute1d_success": "Notification settings were successfully saved.",
"country_select_modal_country_ab": "Abkhazia", "country_select_modal_country_ab": "Abkhazia",

18
app/js/services.js

@ -3516,7 +3516,7 @@ angular.module('myApp.services', ['myApp.i18n', 'izhukov.utils'])
} }
}) })
.service('NotificationsManager', function ($rootScope, $window, $interval, $q, $modal, _, MtpApiManager, AppPeersManager, AppChatsManager, AppUsersManager, IdleManager, Storage, AppRuntimeManager, FileManager, WebPushApiManager) { .service('NotificationsManager', function ($rootScope, $window, $interval, $q, $modal, _, toaster, MtpApiManager, AppPeersManager, AppChatsManager, AppUsersManager, IdleManager, Storage, AppRuntimeManager, FileManager, WebPushApiManager) {
navigator.vibrate = navigator.vibrate || navigator.mozVibrate || navigator.webkitVibrate navigator.vibrate = navigator.vibrate || navigator.mozVibrate || navigator.webkitVibrate
var notificationsMsSiteMode = false var notificationsMsSiteMode = false
@ -3635,6 +3635,22 @@ angular.module('myApp.services', ['myApp.i18n', 'izhukov.utils'])
}) })
return return
} }
if (notificationData.action == 'mute1d') {
MtpApiManager.invokeApi('account.updateDeviceLocked', function () {
period: 86400
}).then(function () {
var toastData = toaster.pop({
type: 'info',
body: _('push_action_mute1d_success'),
bodyOutputType: 'trustedHtml',
clickHandler: function () {
toaster.clear(toastData)
},
showCloseButton: false
})
})
return
}
var peerID = notificationData.custom && notificationData.custom.peerID var peerID = notificationData.custom && notificationData.custom.peerID
console.log('click', notificationData, peerID) console.log('click', notificationData, peerID)
if (peerID) { if (peerID) {

Loading…
Cancel
Save