def check_battery(): status = None remaining = None capacity = None try: state_file = open('/proc/acpi/battery/BAT0/state') info_file = open('/proc/acpi/battery/BAT0/info') for line in state_file: if line.find('remaining') >= 0: temp = line.split(':')[2][:-3] remaining = int(temp.strip()) elif line.find('charging') >= 0: temp = line.split(':')[2] status = temp.strip() for line in info_file: if line.find('last full') >= 0: temp = line.split(':')[2][:-3] capacity = int(temp.strip()) except: fd = open('/sys/class/power_supply/BAT0/charge_full') capacity = int(fd.readline()) fd.close() fd = open('/sys/class/power_supply/BAT0/charge_now') remaining = int(fd.readline()) fd.close() fd = open('/sys/class/power_supply/BAT0/status') status = fd.readline().lower() fd.close() finally: print capacity, remaining, status percentage = int((remaining * 100) / capacity) notification = None if percentage <= 5: notification = Notify.Notification('Critical battery level', 'Battery level under 5%, your PC will shutdown shortly', None) elif percentage <= 10: notification = Notify.Notification('Low battery level', 'Battery level under 10%, connect the charger', None) if notification: notification.show() GObject.timeout_add(60000, check_battery)
def do_source_operation(self, enable_str, source_json, *args): enable = int(enable_str) source = json.loads(source_json) distro = source['distro_value'] log.debug("Enable? %s for source: %s for distro: %s" % (enable, source['name'], distro)) if ppa.is_ppa(source['url']): file_name = '%s-%s' % (ppa.get_source_file_name(source['url']), distro) else: file_name = source['slug'] # TODO these kinds of source should never be featured if not source['component'] and distro: distro = distro + '/' elif not source['component'] and not distro: distro = './' try: result = proxy.set_separated_entry(source['url'], distro, source['component'], source['summary'], enable, file_name) log.debug("Enable source: %s result: %s" % (source['name'], result)) if source['key']: proxy.add_apt_key_from_content(source['key']) if result == 'enabled': notify = Notify.Notification(summary=_('New source has been enabled'), body=_('"%s" is enabled now, Please click the update button to update %s') % (source['name'], self.current_app)) notify.set_property('icon-name', 'ubuntu-tweak') notify.set_hint_string("x-canonical-append", "true") notify.show() self.update_action_button(self.UPDATE_ACTION) except Exception, e: log.error(e) self.update_sources()
def prepare_notify(self): try: from gi.repository import Notify self.has_notifications = True except ImportError: logging.warning ("libnotify not found.") return "libnotify not found" # Work-around Ubuntu's incompatible workaround for Gnome's API breaking mistake. # https://bugzilla.gnome.org/show_bug.cgi?id=702390 old_add_action = Notify.Notification.add_action def new_add_action(*args): try: old_add_action(*args) except TypeError: old_add_action(*(args + (None,))) Notify.Notification.add_action = new_add_action Notify.init('pithos') self.notification = Notify.Notification() self.notification.set_category('x-gnome.music') self.notification.set_hint('desktop-entry', GLib.Variant.new_string('pithos')) caps = Notify.get_server_caps() if 'actions' in caps: logging.info('Notify supports actions') self.supports_actions = True if 'body-markup' in caps: self.escape_markup = True if 'action-icons' in caps: self.notification.set_hint('action-icons', GLib.Variant.new_boolean(True))
def __init__(self, player): self._player = player self._notification = Notify.Notification() self._notification.set_category('x-gnome.music') self._notification.set_hint('action-icons', GLib.Variant('b', True)) self._notification.set_hint('resident', GLib.Variant('b', True)) self._notification.set_hint('desktop-entry', GLib.Variant('s', 'gnome-music')) self._isPlaying = False self._albumArtCache = AlbumArtCache.get_default() self._noArtworkIcon = self._albumArtCache.get_default_icon( IMAGE_SIZE, IMAGE_SIZE) rowStride = self._noArtworkIcon.get_rowstride() hasAlpha = self._noArtworkIcon.get_has_alpha() bitsPerSample = self._noArtworkIcon.get_bits_per_sample() nChannels = self._noArtworkIcon.get_n_channels() data = self._noArtworkIcon.get_pixels() self._noArtworkIconSerialized = GLib.Variant( '(iiibiiay)', (IMAGE_SIZE, IMAGE_SIZE, rowStride, hasAlpha, bitsPerSample, nChannels, data)) self._player.connect('playing-changed', self._on_playing_changed) self._player.connect('current-changed', self._update_track) self._player.connect('thumbnail-updated', self._on_thumbnail_updated)
def send(self, message=None, details=None): if not message: errmsg = "Message not provided" raise usend.ParameterError(errmsg) ntfy = Notify.Notification(summary=message, body=details) ntfy.show()
def _bootstrap_notifications(self): # Check if someone is providing the notification service bus = dbus.SessionBus() try: bus.get_name_owner("org.freedesktop.Notifications") except dbus.exceptions.DBusException: return None notif = None # Bootstrap whatever notifications system we are using if using_gi_notify: logger.debug("Initializing GObject.Notify") if Notify.init(identity): notif = Notify.Notification() notif.set_hint("desktop-entry", GLib.Variant("s", "snapcast_mpris")) notif.set_hint("transient", GLib.Variant("b", True)) else: logger.error( "Failed to init libnotify; disabling notifications") elif using_old_notify: logger.debug("Initializing old pynotify") if pynotify.init(identity): notif = pynotify.Notification("", "", "") notif.set_hint("desktop-entry", "snapcast_mpris") notif.set_hint("transient", True) else: logger.error( "Failed to init libnotify; disabling notifications") return notif
def notify(self, _vte, terminal): """Notify that a terminal did something""" show_notify = False # Don't notify if the user is already looking at this terminal. if terminal.vte.flags() & Gtk.HAS_FOCUS: return True note = Notify.Notification( 'Terminator', 'Activity in: %s' % terminal.get_window_title(), 'terminator') this_time = time.mktime(time.gmtime()) if terminal not in self.last_notifies: show_notify = True else: last_time = self.last_notifies[terminal] if this_time - last_time > 10: show_notify = True if show_notify == True: note.show() self.last_notifies[terminal] = this_time return True
def __changed_enabled(self, settings, key): enabled = settings[key] adjective = WORDS[enabled][0] Imperative = WORDS[not enabled][1] summary = 'CBI reporting is %s' % adjective body = BODY % adjective themed = 'sampler-' + ('enabled' if enabled else 'disabled') note = Notify.Notification(summary=summary, body=body, icon_name=themed) note.set_urgency(Notify.Urgency.LOW) note.set_hint('resident', GLib.Variant.new_boolean(True)) note.set_hint_string('desktop-entry', 'sampler-tray') note.add_action('toggle', Imperative, self.__set_enabled, (settings, key, not enabled)) if not BODY_HYPERLINKS: note.add_action('learn-more', 'Learn More…', self.__learn_more, None) self.close() self.__note = note if self.__show_note(note): GLib.timeout_add_seconds(1, self.__show_note, note)
def show(dev, reason=None, icon=None): """Show a notification with title and text.""" if available and Notify.is_initted(): summary = dev.name # if a notification with same name is already visible, reuse it to avoid spamming n = _notifications.get(summary) if n is None: n = _notifications[summary] = Notify.Notification() if reason: message = reason elif dev.status is None: message = _("unpaired") elif bool(dev.status): message = dev.status.to_string() or _("connected") else: message = _("offline") # we need to use the filename here because the notifications daemon # is an external application that does not know about our icon sets icon_file = _icons.device_icon_file(dev.name, dev.kind) if icon is None \ else _icons.icon_file(icon) n.update(summary, message, icon_file) urgency = Notify.Urgency.LOW if dev.status else Notify.Urgency.NORMAL n.set_urgency(urgency) try: # if _log.isEnabledFor(_DEBUG): # _log.debug("showing %s", n) n.show() except Exception: _log.exception("showing %s", n)
def on_prepare(self): try: from gi.repository import Notify self.has_notify = True except ImportError: logging.warning("libnotify not found.") return if (Notify.VERSION_MAJOR, Notify.VERSION_MINOR, Notify.VERSION_MICRO) < (0, 7, 6): old_add_action = Notify.Notification.add_action Notify.Notification.add_action = lambda *args: old_add_action(*( args + (None, ))) Notify.init('Pithos') self.notification = Notify.Notification() self.notification.set_category('x-gnome.music') self.notification.set_hint_string('desktop-icon', 'pithos') caps = Notify.get_server_caps() if 'actions' in caps: logging.info('Notify supports actions') self.supports_actions = True if 'action-icons' in caps: self.notification.set_hint('action-icons', GLib.Variant.new_boolean(True))
def _notify(self, message, icon, title="Caffeine"): """Easy way to use pynotify""" try: Notify.init("Caffeine") if self.note: self.note.update(title, message, icon) else: self.note = Notify.Notification(title, message, icon) # Notify OSD doesn't seem to work when sleep is prevented if self.screenSaverCookie is not None and \ self.__inhibition_successful: self.ssProxy.UnInhibit(self.screenSaverCookie) self.note.show() if self.screenSaverCookie is not None and \ self.__inhibition_successful: self.screenSaverCookie = \ self.ssProxy.Inhibit("Caffeine", "User has requested that Caffeine " + "disable the screen saver") except Exception as e: logging.error("Exception occurred:\n" + " " + str(e)) logging.error("Exception occurred attempting to display " + "message:\n" + message) finally: return False
def show(summary, body, icon_name='dialog-error', timeout=5000): notification = Notify.Notification(summary=summary, body=body, icon_name=icon_name) notification.set_timeout(timeout) notification.show()
def do_source_enable(self, iter, enable): ''' Do the really source enable or disable action by iter Only emmit signal when source is changed ''' model = self.get_model() id = model.get_value(iter, self.COLUMN_ID) url = model.get_value(iter, self.COLUMN_URL) icon = model.get_value(iter, self.COLUMN_LOGO) comment = model.get_value(iter, self.COLUMN_NAME) pre_status = self.get_sourcelist_status(url) result = SOURCE_PARSER.set_enable(id, enable) log.debug("Setting source %s (%d) to %s, result is %s" % (comment, id, str(enable), result)) if result == 'enabled': model.set(iter, self.COLUMN_ENABLED, True) else: model.set(iter, self.COLUMN_ENABLED, False) if pre_status != enable: self.emit('sourcechanged') if enable: notify = Notify.Notification( summary=_('New source has been enabled'), body= _('%s is enabled now, Please click the refresh button to update the application cache.' ) % comment) notify.set_icon_from_pixbuf(icon) notify.set_hint_string("x-canonical-append", "") notify.show()
def on_copy_button_clicked(widget, text): notify = Notify.Notification() notify.update(summary=_('Error message has been copied'), body=_('Now click "Report" to enter the bug ' 'report website. Make sure to attach the ' 'error message in "Further information".'), icon='ubuntu-cleaner') notify.show()
def __init__(self): Notify.init(_("Birdie")) self.notification = Notify.Notification() #self.notification.set_category('x-gnome.network') self.notification.set_hint('action-icons', GLib.Variant('b', True)) self.notification.set_hint('resident', GLib.Variant('b', True)) self.notification.set_hint('desktop-entry', GLib.Variant('s', 'birdie'))
def __init__(self, player): self._player = player self._notification = Notify.Notification() self._notification.set_category('x-gnome.podcasts') self._notification.set_hint('action-icons', GLib.Variant('b', True)) self._notification.set_hint('resident', GLib.Variant('b', True)) self._notification.set_hint('desktop-entry', GLib.Variant('s', 'gnome-podcasts'))
def init_notify_cb(self): self.notifycaps = Notify.get_server_caps() self.notify = Notify.Notification() self.notify.set_property( 'icon-name', os.path.join(self.m.get_prefix(), 'monajat.svg')) self.notify.set_property('summary', _("Monajat")) if 'actions' in self.notifycaps: self.notify.add_action("previous", _("Back"), self.notify_cb, None) self.notify.add_action("next", _("Forward"), self.notify_cb, None) self.notify.add_action("copy", _("copy"), self.notify_cb, None)
def on_copy_button_clicked(widget, text): atom = Gdk.atom_intern('CLIPBOARD', True) clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), atom) clipboard.set_text(text, -1) notify = Notify.Notification() notify.update(summary=_('Error message has been copied'), body=_('Now click "Report" to enter the bug ' 'report website. Make sure to attach the ' 'error message in "Further information".'), icon='ubuntu-tweak') notify.show()
def __init__(self): """ Init notification object with lollypop infos """ self._caps = Notify.get_server_caps() self._notification = Notify.Notification() self._notification.set_category('x-gnome.music') self._notification.set_hint('desktop-entry', GLib.Variant('s', 'lollypop')) self._set_actions() Lp().player.connect('current-changed', self._on_current_changed)
def __init__(self): caps = Notify.get_server_caps() self._notification = Notify.Notification() self._notification.set_category('x-gnome.music') if "action-icons" in caps: self._notification.set_hint('action-icons', GLib.Variant('b', True)) self._notification.set_hint('desktop-entry', GLib.Variant('s', 'lollypop')) if "actions" in caps: self._notification.add_action('media-skip-backward', _("Previous"), self._go_previous, None) self._notification.add_action('media-skip-forward', _("Next"), self._go_next, None) Objects.player.connect('current-changed', self._on_current_changed)
def check_times(self, terminal): """Check if this terminal has gone silent""" time_now = time.mktime(time.gmtime()) if terminal not in self.last_activities: dbg('Terminal %s has no last activity' % terminal) return True dbg('seconds since last activity: %f (%s)' % (time_now - self.last_activities[terminal], terminal)) if time_now - self.last_activities[terminal] >= inactive_period: del (self.last_activities[terminal]) note = Notify.Notification( 'Terminator', 'Silence in: %s' % terminal.get_window_title(), 'terminator') note.show() return True
def __init__(self, player): self._player = player self._notification = Notify.Notification() self._notification.set_category('x-gnome.music') self._notification.set_hint('action-icons', GLib.Variant('b', True)) self._notification.set_hint('resident', GLib.Variant('b', True)) self._notification.set_hint('desktop-entry', GLib.Variant('s', 'gnome-music')) self._isPlaying = False self._albumArtCache = AlbumArtCache.get_default() self._noArtworkIcon = self._albumArtCache.get_default_icon( IMAGE_SIZE, IMAGE_SIZE) self._noArtworkIconSerialized = None
def popup(self, status): """popups up notification of finished torrent""" if not deluge.common.windows_check(): try: from gi.repository import Notify except: log.warning("pynotify is not installed") else: if not Notify.init("Deluge"): return title = deluge.common.xml_encode(_("Torrent complete")) message = deluge.common.xml_encode( "%s\n%s %i %s" % (status["name"], _("Including"), status["num_files"], _("files"))) self.note = Notify.Notification(title, message) self.note.set_icon_from_pixbuf(common.get_logo(48)) if not self.note.show(): log.warning("pynotify failed to show notification")
def __init__(self, player): self._player = player self._notification = Notify.Notification() self._notification.set_category('x-gnome.music') self._notification.set_hint('action-icons', GLib.Variant('b', True)) self._notification.set_hint('resident', GLib.Variant('b', True)) self._notification.set_hint('desktop-entry', GLib.Variant('s', 'gnome-music')) self._isPlaying = False self._albumArtCache = AlbumArtCache.get_default() self._symbolicIcon = self._albumArtCache.make_default_icon( IMAGE_SIZE, IMAGE_SIZE) self._player.connect('playing-changed', self._on_playing_changed) self._player.connect('current-changed', self._update_track)
def on_package_work_finished(self, transaction, status, kwargs): unset_busy(self) parent = kwargs['parent'] url_list = kwargs['url_list'] for url in url_list: #TODO remove vendor key result = proxy.purge_source(url, '') log.debug("Set source: %s to %s" % (url, str(result))) self.sourceview.to_purge = [] self.update_sourceview() notify = Notify.Notification( summary=_('PPA has been purged'), body=_( 'It is highly recommend to do a "Refresh" source operation.')) notify.set_icon_from_pixbuf(self.get_pixbuf(size=48)) notify.set_hint_string("x-canonical-append", "") notify.show()
def __init__(self, params): self._notification = None if params["notify"]: if using_gi_notify: logger.debug("Initializing GObject.Notify") if Notify.init(identity): self._notification = Notify.Notification() self._notification.set_hint("desktop-entry", GLib.Variant("s", "mpdris2")) self._notification.set_hint("transient", GLib.Variant("b", True)) else: logger.error("Failed to init libnotify; disabling notifications") elif using_old_notify: logger.debug("Initializing old pynotify") if pynotify.init(identity): self._notification = pynotify.Notification("", "", "") self._notification.set_hint("desktop-entry", "mpdris2") self._notification.set_hint("transient", True) else: logger.error("Failed to init libnotify; disabling notifications")
def startTimer(alltimes, startingNow): import gi gi.require_version('Notify', '0.7') from gi.repository import Notify import time Notify.init("Timer") notifier = Notify.Notification().new("") def notifyAtTime(target, notifier, text): if target < datetime.datetime.now(): raise (ValueError("Tried to create a notification in the past?")) delta = (target - datetime.datetime.now()).seconds time.sleep(delta) notifier.update("Timer", text) notifier.show() if not startingNow: timenow = datetime.datetime.now() if alltimes[0] < timenow.replace(second=0): alltimes = [i for i in alltimes if timenow < i] if len(alltimes) % 2 == 1: alltimes.pop() if len(alltimes) == 0: raise (ArithmeticError( "Notifier cannot be started if work times have already occured" )) else: time.sleep((alltimes[0] - datetime.datetime.now()).seconds) index = 0 for i in alltimes: next = alltimes[index + 1].strftime("%H:%M") if i == alltimes[0]: notifier.update("Timer", "Work until " + next) notifier.show() elif index % 2 == 0: notifyAtTime(i, notifier, "Work until " + next) else: notifyAtTime(i, notifier, "Rest until " + next) index += 1
def alert(reason, icon=None): assert reason if available and Notify.is_initted(): n = _notifications.get(NAME) if n is None: n = _notifications[NAME] = Notify.Notification() # we need to use the filename here because the notifications daemon # is an external application that does not know about our icon sets icon_file = _icons.icon_file(NAME.lower()) if icon is None \ else _icons.icon_file(icon) n.update(NAME, reason, icon_file) n.set_urgency(Notify.Urgency.NORMAL) try: # if _log.isEnabledFor(_DEBUG): # _log.debug("showing %s", n) n.show() except Exception: _log.exception("showing %s", n)
def start_service(mypath, is_recursive): # Stop currently running service if exist if is_service_running(): stop_service() # Create notify object Notify.init("imgmatch") notify = Notify.Notification() # Start new daemon with daemon.DaemonContext( working_directory=os.getcwd(), pidfile=lockfile.FileLock(DAEMON_LOCK_FILE) ): print_log("Daemon hajimaru yo~") # Write pid to temp file with open(DAEMON_PID_FILE, 'w') as tpid: tpid.write(str(os.getpid())) # Run the service service(mypath, is_recursive, notify)
def show(dev, reason=None, icon=None, progress=None): """Show a notification with title and text. Optionally displays the `progress` integer value in [0, 100] as a progress bar.""" if available and Notify.is_initted(): summary = dev.name # if a notification with same name is already visible, reuse it to avoid spamming n = _notifications.get(summary) if n is None: n = _notifications[summary] = Notify.Notification() if reason: message = reason elif dev.status is None: message = _('unpaired') elif bool(dev.status): message = dev.status.to_string() or _('connected') else: message = _('offline') # we need to use the filename here because the notifications daemon # is an external application that does not know about our icon sets icon_file = _icons.device_icon_file( dev.name, dev.kind) if icon is None else _icons.icon_file(icon) n.update(summary, message, icon_file) urgency = Notify.Urgency.LOW if dev.status else Notify.Urgency.NORMAL n.set_urgency(urgency) n.set_hint('desktop-entry', GLib.Variant('s', NAME.lower())) if progress: n.set_hint('value', GLib.Variant('i', progress)) try: # if _log.isEnabledFor(_DEBUG): # _log.debug("showing %s", n) n.show() except Exception: _log.exception('showing %s', n)