view src/browser/sat_browser/notification.py @ 502:4aa627b059df

browser_side: categories of the menus can be "flattened": - add the parameter "flat_level" to GenericMenuBar - the items of flattened sub-menus are displayed in the parent menu XXX: the implementation covers the current needs but is not fully completed: - the flattened categories of all levels are displayed the same way - items of flattened categories are appended to the parent menus instead of being inserted
author souliane <souliane@mailoo.org>
date Wed, 13 Aug 2014 15:06:40 +0200
parents 97c72fe4a5f2
children e11e34ac0f67
line wrap: on
line source

from __pyjamas__ import JS, wnd
from sat.core.log import getLogger
log = getLogger(__name__)
from sat.core.i18n import _

from pyjamas import Window
from pyjamas.Timer import Timer

import dialog

TIMER_DELAY = 5000


class Notification(object):
    """
    If the browser supports it, the user allowed it to and the tab is in the
    background, send desktop notifications on messages.

    Requires both Web Notifications and Page Visibility API.
    """

    def __init__(self):
        self.enabled = False
        user_agent = None
        notif_permission = None
        JS("""
        if (!('hidden' in document))
            document.hidden = false;

        user_agent = navigator.userAgent

        if (!('Notification' in window))
            return;

        notif_permission = Notification.permission

        if (Notification.permission === 'granted')
            this.enabled = true;

        else if (Notification.permission === 'default') {
            Notification.requestPermission(function(permission){
                if (permission !== 'granted')
                    return;

                self.enabled = true; //need to use self instead of this
            });
        }
        """)

        if "Chrome" in user_agent and notif_permission not in ['granted', 'denied']:
            self.user_agent = user_agent
            self._installChromiumWorkaround()

        wnd().onfocus = self.onFocus
        # wnd().onblur = self.onBlur
        self._notif_count = 0
        self._orig_title = Window.getTitle()

    def _installChromiumWorkaround(self):
        # XXX: Workaround for Chromium behaviour, it's doens't manage requestPermission on onLoad event
        # see https://code.google.com/p/chromium/issues/detail?id=274284
        # FIXME: need to be removed if Chromium behaviour changes
        try:
            version_full = [s for s in self.user_agent.split() if "Chrome" in s][0].split('/')[1]
            version = int(version_full.split('.')[0])
        except (IndexError, ValueError):
            log.warning("Can't find Chromium version")
            version = 0
        log.info("Chromium version: %d" % (version,))
        if version < 22:
            log.info("Notification use the old prefixed version or are unmanaged")
            return
        if version < 32:
            dialog.InfoDialog(_("Notifications activation for Chromium"), _('You need to activate notifications manually for your Chromium version.<br/>To activate notifications, click on the favicon on the left of the address bar')).show()
            return

        log.info("==> Installing Chromium notifications request workaround <==")
        self._old_click = wnd().onclick
        wnd().onclick = self._chromiumWorkaround

    def _chromiumWorkaround(self):
        log.info("Activating workaround")
        JS("""
            Notification.requestPermission(function(permission){
                if (permission !== 'granted')
                    return;
                self.enabled = true; //need to use self instead of this
            });
        """)
        wnd().onclick = self._old_click

    def onFocus(self):
        Window.setTitle(self._orig_title)
        self._notif_count = 0

    # def onBlur(self):
    #     pass

    def isHidden(self):
        JS("""return document.hidden;""")

    def _notify(self, title, body, icon):
        if not self.enabled:
            return
        notification = None
        JS("""
           notification = new Notification(title, {body: body, icon: icon});
           // Probably won’t work, but it doesn’t hurt to try.
           notification.addEventListener('click', function() {
               window.focus();
           });
           """)
        notification.onshow = lambda: Timer(TIMER_DELAY, lambda timer: notification.close())

    def highlightTab(self):
        self._notif_count += 1
        Window.setTitle("%s (%d)" % (self._orig_title, self._notif_count))

    def notify(self, title, body, icon='/media/icons/apps/48/sat.png'):
        if self.isHidden():
            self._notify(title, body, icon)
            self.highlightTab()