def notification(self): while(True): live_scores, valid = Fixtures().fixture() for score in live_scores: match_time = score['time'] status = score['status'] team = score['team'] score = score['score'] score_time = score + ' (Time:' + match_time + ')' if status != 1: if status == 3: score_time = score + ' (FT)' elif status == 4: score_time = score + ' (HT)' Notify.init("Live Score") send_notification = Notify.Notification.new(team, score_time, ) send_notification.set_icon_from_pixbuf(self._icon) send_notification.show() time.sleep(3) send_notification.close() Notify.uninit() if not valid: break time.sleep(300)
def let_it_rain(): GObject.threads_init() Gst.init(None) signal.signal(signal.SIGINT, signal.SIG_DFL) Notify.init("silver-rain") # Create system directories if not os.path.exists(IMG_DIR): os.makedirs(IMG_DIR) # Initialize config config.setup() # Create directory for recordings if not os.path.exists(config.recs_dir): os.makedirs(config.recs_dir) # Load css css_load() # Init translation set_translation() # Init application silver_app = SilverApp() # Setup dbus service service = SilverService(silver_app) # Run loop Gtk.main() # Cleanup silver_app.clean() Notify.uninit()
def autoSuspender(self, minPercent=5): # update even full capacity in case the battery has been changed self.full = int(cat("/sys/class/power_supply/BAT0/energy_full")) self.update() # hibernate only if battery is discharging if self.state != "Discharging": return {} # return empty dict, main loop expects it # test if everything is OK for var in (self.full, self.now, self.state, self.percent): if var is None: return {} # return empty dict, main loop expects it # test battery level if self.percent <= minPercent: Notify.init("Hibernation") battLevel = Notify.Notification.new("Warning:", "Battery level at " + str(self.percent) + "%.", "") battLevel.set_urgency(Notify.Urgency.CRITICAL) battLevel.show() warning = Notify.Notification.new("Warning:", "Hibernation in 10 seconds...", "") warning.set_urgency(Notify.Urgency.CRITICAL) warning.show() time.sleep(10) battLevel.close() warning.close() Notify.uninit() subprocess.call("systemctl hibernate", shell=True) return {} # return empty dict, main loop expects it
def cleanup(): os.system("rm -f -R %s" % dirpath) os.system("rm -f %s" % static_name + ".bun") #os.system("rm -f %s" % static_name) os.system("rm -f %s" % static_name + ".desktop") os.system("rm -f Applications") Notify.uninit()
def notif(self, notif_icon): global _notification_header global _notification_description # Get icon try: os.remove("icon_cache.png") except: print "Creating icon cache..." file_object = open("icon_cache.png", "a") while True: data = notif_icon.file.read(8192) if not data: break file_object.write(data) file_object.close() # Ensure the notification is not a duplicate if (_notification_header != cherrypy.request.headers['NOTIF-HEADER']) or (_notification_description != cherrypy.request.headers['NOTIF-DESCRIPTION']): # Get notification data from HTTP header _notification_header = cherrypy.request.headers['NOTIF-HEADER'].replace('\x00', '').decode('iso-8859-1', 'replace').encode('utf-8') _notification_description = cherrypy.request.headers['NOTIF-DESCRIPTION'].replace('\x00', '').decode('iso-8859-1', 'replace').encode('utf-8') # Send the notification notif = Notify.Notification.new(_notification_header, _notification_description, icon_path) try: notif.show() except: # Workaround for org.freedesktop.DBus.Error.ServiceUnknown Notify.uninit() Notify.init("com.willhauck.linconnect") notif.show() return "true"
def get_cpu_speeds(self): message = '' try: r = requests.post('https://www-wohnheim.uni-regensburg.de/utils/login.py/checkAuthentication', data=payload) soup = BeautifulSoup(r.text) title = soup.findAll('title')[0].get_text() login_page = title.find('Login')>0 if(login_page): notify.init('indicator-cpuspeed') notify.Notification.new("<b>Login failed</b>", "<b>Change password?</b>", None).show() notify.uninit() rzdatatable = soup.find("table", {"id": "rzdatatable"}) data = rzdatatable.findAll('tr')[1] wohnheim = data.findAll('td')[0].get_text() zimmer = data.findAll('td')[1].get_text() status = data.findAll('td')[2].span.get_text() empfangen = data.findAll('td')[3].get_text() gesendet = data.findAll('td')[4].get_text() summe = data.findAll('td')[5].get_text() limit = data.findAll('td')[6].get_text() # print(wohnheim + "(" + zimmer + "), status: " + status) # print("Volumen: " + str(summe) + "mb von " + str(limit) + "mb (" + str(round(100*float(summe)/float(limit),2)) + "%), davon " + gesendet + "mb gesendet und " + empfangen + "mb empfangen.") message = str(summe) except requests.ConnectionError: message = 'No Connection' return message
def _exit(self, widget): """Close Feedindicator. Args: widget: Gtk widget """ Notify.uninit() Gtk.main_quit()
def connectClicked(self, doesProfileExist, profileName): '''process a connection request from the user''' if doesProfileExist is 1: select = self.APList.get_selection() networkSSID = self.getSSID(select) n = Notify.Notification.new("Found existing profile.", "NetCTL found an existing profile for this network. Connecting to " + networkSSID + " using profile " + profileName) n.show() netinterface = self.interfaceName InterfaceCtl.down(self, netinterface) NetCTL.stopall(self) NetCTL.start(self, profileName) n = Notify.Notification.new("Connected to new network!", "You are now connected to " + networkSSID, "dialog-information") n.show() elif doesProfileExist == 0: if self.NoWifiMode == 0: select = self.APList.get_selection() networkSSID = self.getSSID(select) print("nSSID = " + networkSSID) profile = "netgui_" + networkSSID print("profile = " + profile) netinterface = self.interfaceName if os.path.isfile(conf_dir + profile): InterfaceCtl.down(self, netinterface) NetCTL.stopall(self) NetCTL.start(profile) n = Notify.Notification.new("Connected to new network!", "You are now connected to " + networkSSID, "dialog-information") n.show() else: networkSecurity = self.getSecurity(select) key = self.get_network_pw() CreateConfig(networkSSID, self.interfaceName, networkSecurity, key) try: InterfaceCtl.down(self, netinterface) NetCTL.stopall(self) NetCTL.start(self, profile) n = Notify.Notification.new("Connected to new network!", "You are now connected to " + networkSSID, "dialog-information") n.show() except Exception as e: n = Notify.Notification.new("Error!", "There was an error. The error was: " + str(e) + ". Please report an issue at the github page if it persists.", "dialog-information") n.show() Notify.uninit() elif self.NoWifiMode == 1: select = self.APList.get_selection() NWMprofile = self.getSSID(select) netinterface = GetInterface() try: InterfaceCtl.down(self, netinterface) NetCTL.stopall(self) NetCTL.start(self, NWMprofile) n = Notify.Notification.new("Connected to new profile!", "You are now connected to " + NWMprofile, "dialog-information") n.show() except: n = Notify.Notification.new("Error!", "There was an error. Please report an issue at the github page if it persists.", "dialog-information") n.show() Notify.uninit() self.startScan(self)
def main(self): GObject.threads_init() Gdk.threads_init() try: Gtk.main() except KeyboardInterrupt: Gtk.main_quit() Notify.uninit()
def main(self, hook_func=None, skip_workdir_scan=False): """ Where everything start. """ parser = argparse.ArgumentParser( description='Manages scanned documents and PDFs' ) parser.add_argument('--version', action='version', version=str(__version__)) parser.add_argument( "--debug", "-d", default=os.getenv("PAPERWORK_VERBOSE", "INFO"), choices=LogTracker.LOG_LEVELS.keys(), help="Set verbosity level. Can also be set via env" " PAPERWORK_VERBOSE (e.g. export PAPERWORK_VERBOSE=INFO)" ) args, unknown_args = parser.parse_known_args(sys.argv[1:]) LogTracker.init() logging.getLogger().setLevel(LogTracker.LOG_LEVELS.get(args.debug)) set_locale() if hasattr(GLib, "unix_signal_add"): GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, self.quit_nicely, None) GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM, self.quit_nicely, None) backend_state = paperwork_backend.init() logger.info("Initializing pyinsane ...") pyinsane2.init() try: logger.info("Initializing libnotify ...") Notify.init("Paperwork") self.config = load_config() self.config.read() self.main_win = MainWindow( self.config, self.main_loop, not skip_workdir_scan, flatpak=backend_state['flatpak'] ) if hook_func: hook_func(self.config, self.main_win) self.main_loop.run() logger.info("Writing configuration ...") self.config.write() logger.info("Stopping libnotify ...") Notify.uninit() finally: logger.info("Stopping Pyinsane ...") pyinsane2.exit() logger.info("Good bye")
def shutdown(*args, **kwargs): print 'Finishing app...' try: os.remove('/tmp/fsmtp_preview.html') except OSError: print "Temp file not found. Moving..." Notify.uninit() stop_event.set() Gtk.main_quit()
def main(): args = parse_args() Notify.init(argv[0]) notification = Notify.Notification.new(summary=TITLE) show_notification(notification, 'Eyewatch daemon started!', args.icon) while True: sleep(int(args.timer)) text = get_random_message(MESSAGES) show_notification(notification, text, args.icon) Notify.uninit()
def __del__(self): if not self.enabled: return log.info('Exiting...') self.hub.close() Notify.Notification.new("fedmsg", "deactivated", "").show() Notify.uninit() shutil.rmtree(self.cache_dir, ignore_errors=True) self.enabled = False try: reactor.stop() except ReactorNotRunning: pass
def growl(text): """send a growl notification if on mac osx (use GNTP or the growl lib)""" if platform.system() == 'Darwin': # gntplib.publish("Hitman", "Status Update", "Hitman", text=text) # print("GNTP lib was unpublished from pypi. We're working on notification center support. Pull requests welcome.") # if Popen(['which', 'growlnotify'], stdout=PIPE).communicate()[0]: # os.system("growlnotify -t Hitman -m %r" % str(text)) import pync pync.Notifier.notify(text, title="Hitman") elif platform.system() == 'Linux': notified = False try: logger.debug("Trying to import pynotify") import pynotify pynotify.init("Hitman") n = pynotify.Notification("Hitman Status Report", text) n.set_timeout(pynotify.EXPIRES_DEFAULT) n.show() notified = True except ImportError: logger.debug("Trying notify-send") print "trying to notify-send" if Popen(['which', 'notify-send'], stdout=PIPE).communicate()[0]: # Do an OSD-Notify # notify-send "Totem" "This is a superfluous notification" os.system("notify-send \"Hitman\" \"%r\" " % str(text)) notified = True if not notified: try: from gi.repository import Notify Notify.init("Hitman") #TODO have Icon as third argument. notification = Notify.Notification.new("Hitman", text) notification.show() Notify.uninit() notified = True except ImportError: pass elif platform.system() == 'Haiku': os.system("notify --type information --app Hitman --title 'Status Report' '%s'" % str(text)) elif platform.system() == 'Windows': try: # gntplib.publish("Hitman", "Status Update", "Hitman", text=text) print("Sorry Growl For Windows users. GNTPlib was pulled from pypi. We're not aware of compeditors to growl for windows at this time.") except: print("Install Growl For windows if you want notifications! \n http://www.growlforwindows.com/gfw/") else: pass
def notify_send(input_string): try: app_name, urgency, category, summary, body = input_string.split('|') except ValueError: print("Split the five parametered msg via pipe") return False Notify.init(app_name) notification = Notify.Notification.new(summary, body) notification.set_urgency(int(urgency)) notification.show() del notification Notify.uninit() return True
def growl(text): """send native notifications where supported. Growl is gone.""" if platform.system() == 'Darwin': import pync pync.Notifier.notify(text, title="Hitman") elif platform.system() == 'Linux': notified = False try: logger.debug("Trying to import pynotify") import pynotify pynotify.init("Hitman") n = pynotify.Notification("Hitman Status Report", text) n.set_timeout(pynotify.EXPIRES_DEFAULT) n.show() notified = True except ImportError: logger.debug("Trying notify-send") # print("trying to notify-send") if Popen(['which', 'notify-send'], stdout=PIPE).communicate()[0]: # Do an OSD-Notify # notify-send "Totem" "This is a superfluous notification" os.system("notify-send \"Hitman\" \"%r\" " % str(text)) notified = True if not notified: try: logger.info("notificatons gnome gi???") import gi gi.require_version('Notify', '0.7') from gi.repository import Notify Notify.init("Hitman") # TODO have Icon as third argument. notification = Notify.Notification.new("Hitman", text) notification.show() Notify.uninit() notified = True except ImportError: logger.exception() elif platform.system() == 'Haiku': os.system("notify --type information --app Hitman --title 'Status Report' '%s'" % str(text)) elif platform.system() == 'Windows': try: from win10toast import ToastNotifier toaster = ToastNotifier() toaster.show_toast(text, "Hitman") # gntplib.publish("Hitman", "Status Update", "Hitman", text=text) except Exception: logger.exception()
def quite(self): # Notify.uninit() GLib.idle_add(lambda: Notify.uninit()) # notification = Notification() # notification.show(10) # Gtk.main()
def connectClicked(self, menuItem): print(str(self.NoWifiMode)) if self.NoWifiMode == 0: select = self.APList.get_selection() networkSSID = self.getSSID(select) profile = "netgui_" + networkSSID netinterface = GetInterface() if os.path.isfile(conf_dir + profile): InterfaceCtl.down(self, netinterface) NetCTL.stopall(self) NetCTL.start(self, profile) n = Notify.Notification.new("Connected to new network!", "You are now connected to " + networkSSID, "dialog-information") n.show() else: networkSecurity = self.getSecurity(select) key = get_network_pw(self, "Please enter network password", "Network Password Required.") CreateConfig(networkSSID, self.interfaceName, networkSecurity, key) try: InterfaceCtl.down(self, netinterface) NetCTL.stopall(self) NetCTL.start(self, profile) n = Notify.Notification.new("Connected to new network!", "You are now connected to " + networkSSID, "dialog-information") n.show() #wx.MessageBox("You are now connected to " + # str(nameofProfile).strip() + ".", "Connected.") except: #wx.MessageBox("There has been an error, please try again. If" # " it persists, please contact Cody Dostal at " # "[email protected].", "Error!") n = Notify.Notification.new("Error!", "There was an error. Please report an issue at the github page if it persists.", "dialog-information") n.show() Notify.uninit() elif self.NoWifiMode == 1: select = self.APList.get_selection() NWMprofile = self.getSSID(select) netinterface = GetInterface() try: InterfaceCtl.down(self, netinterface) NetCTL.stopall(self) NetCTL.start(self, NWMprofile) n = Notify.Notification.new("Connected to new profile!", "You are now connected to " + NWMprofile, "dialog-information") n.show() except: n = Notify.Notification.new("Error!", "There was an error. Please report an issue at the github page if it persists.", "dialog-information") n.show() Notify.uninit()
def notif(self, notificon): global _notification_header global _notification_description # Get icon try: os.remove(icon_path) except: print("Creating icon cache...") file_object = open(icon_path, "a") while True: data = notificon.file.read(8192) if not data: break file_object.write(str(data)) file_object.close() # Ensure the notification is not a duplicate if (_notification_header != cherrypy.request.headers['NOTIFHEADER']) \ or (_notification_description != cherrypy.request.headers['NOTIFDESCRIPTION']): # Get notification data from HTTP header try: _notification_header = base64.urlsafe_b64decode(cherrypy.request.headers['NOTIFHEADER']) _notification_description = base64.urlsafe_b64decode(cherrypy.request.headers['NOTIFDESCRIPTION']) except: # Maintain compatibility with old application _notification_header = cherrypy.request.headers['NOTIFHEADER'].replace('\x00', '').decode('iso-8859-1', 'replace').encode('utf-8') _notification_description = cherrypy.request.headers['NOTIFDESCRIPTION'].replace('\x00', '').decode('iso-8859-1', 'replace').encode('utf-8') # Send the notification notif = Notify.Notification.new(_notification_header, _notification_description, icon_path) w.post(_notification_header, _notification_description) #a=open("abc.txt","a+") #a.write("\n"+ _notification_header+" >> "+_notification_description+"\n") if parser.has_option('other', 'notify_timeout'): notif.set_timeout(parser.getint('other', 'notify_timeout')) try: notif.show() except: # Workaround for org.freedesktop.DBus.Error.ServiceUnknown Notify.uninit() Notify.init("com.harshad.linconnect") notif.show() return "true"
def notif(self, notificon): global _notification_header global _notification_description # Get notification data from HTTP header try: new_notification_header = base64.urlsafe_b64decode(cherrypy.request.headers['NOTIFHEADER']) new_notification_description = base64.urlsafe_b64decode(cherrypy.request.headers['NOTIFDESCRIPTION']) except: # Maintain compatibility with old application new_notification_header = cherrypy.request.headers['NOTIFHEADER'].replace('\x00', '').decode('iso-8859-1', 'replace').encode('utf-8') new_notification_description = cherrypy.request.headers['NOTIFDESCRIPTION'].replace('\x00', '').decode('iso-8859-1', 'replace').encode('utf-8') # Ensure the notification is not a duplicate if (_notification_header != new_notification_header) \ or (_notification_description != new_notification_description): _notification_header = new_notification_header _notification_description = new_notification_description # Icon should be small enough to fit into modern PCs RAM. # Alternatively, can do this in chunks, twice: first to count MD5, second to copy the file. icon_data = notificon.file.read() icon_path = icon_path_format % hashlib.md5(icon_data).hexdigest() if not os.path.isfile(icon_path): with open(icon_path, 'w') as icon_file: icon_file.write(icon_data) # Send the notification notif = Notify.Notification.new(_notification_header, _notification_description, icon_path) # Add 'value' hint to display nice progress bar if we see percents in the notification percent_match = re.search(r'(1?\d{2})%', _notification_header + _notification_description) if percent_match: notif.set_hint('value', GLib.Variant('i', int(percent_match.group(1)))) if parser.has_option('other', 'notify_timeout'): notif.set_timeout(parser.getint('other', 'notify_timeout')) try: notif.show() except: # Workaround for org.freedesktop.DBus.Error.ServiceUnknown Notify.uninit() Notify.init("com.willhauck.linconnect") notif.show() return "true"
def stop(self): if not self.enabled: return self.enabled = False try: for note in self.notifications: note.close() except GLib.GError: # Bug 1053160 pass Notify.uninit() super(FedmsgNotifyService, self).stop() shutil.rmtree(self.cache_dir, ignore_errors=True) if os.path.exists(pidfile): os.unlink(pidfile)
def notify(title, body=None, icon=None): try: import gi gi.require_version('Notify', '0.7') from gi.repository import Notify from gi.repository import GdkPixbuf except: pass Notify.init(APP_NAME) notification = Notify.Notification.new(title, body) if icon: image = GdkPixbuf.Pixbuf.new_from_file(icon) notification.set_icon_from_pixbuf(image) notification.set_image_from_pixbuf(image) notification.show() Notify.uninit()
def __del__(self): if not self.enabled: return self.enabled = False for note in self.notifications: note.close() Notify.uninit() self.hub.close() try: reactor.stop() except ReactorNotRunning: pass shutil.rmtree(self.cache_dir, ignore_errors=True) if os.path.exists(pidfile): os.unlink(pidfile)
def printscore(scorediv): score = "" for runs in scorediv[0]: try: if runs.name == 'span': score+=runs.get_text() else: score += runs except: pass Notify.init("IPL T20") notification = Notify.Notification.new(score) notification.show() time.sleep(10) print score + "\n" Notify.uninit() notification.close() return
def quit(self, _: Gtk.MenuItem) -> None: self.logger.debug("Exiting...") self.logger.debug("Stopping FS monitor thread...") if self.fs_monitor.is_alive(): self.fs_monitor.stop() self.logger.debug("Stopping update checker thread...") if self.update_checker.is_alive(): self.update_checker.stop() self.logger.debug("Stopping MiniDLNA runner thread...") if self.runner.is_running(): self.stop_minidlna() self.logger.debug("Stopping Notify...") Notify.uninit() self.logger.debug("Exiting main loop...") self.mainloop.quit()
def main(): parser = argparse.ArgumentParser('twnotify') parser.add_argument( '-u', '--username', dest='username', help='Twitch username', required=True ) parser.add_argument( '--interval', dest='interval', type=int, default=120, help='The interval to check for new online streams' ) parser.add_argument( '--logfile', dest='logfile', default=None ) ns = parser.parse_args() if ns.logfile: with open(ns.logfile, 'a') as f: pass Notify.init('twnotify') while True: try: mainloop(ns.username, interval=ns.interval) except KeyboardInterrupt: break except Exception: if ns.logfile: with open(ns.logfile, 'a') as f: f.write(datetime.datetime.now().isoformat(sep=' ')) traceback.print_exc(file=f) traceback.print_exc(file=sys.stderr) Notify.uninit()
def notify_stream(stream): with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as icon: if stream['channel']['logo']: download(stream['channel']['logo'], icon) n = Notify.Notification.new( '{0} just went live!'.format(stream['channel']['display_name']), '{0} is playing {1}:\n{2}\n{3}'.format( stream['channel']['display_name'], stream['game'], stream['channel']['status'], stream['channel']['url'] ), icon.name ) n.set_category('presence.online') try: n.show() except GLib.Error: # sometimes this happens # g-dbus-error-quark: GDBus.Error:org.freedesktop.DBus.Error.ServiceUnknown Notify.uninit() Notify.init('twnotify') n.show()
def quit(self, widget): notify.uninit() Gtk.main_quit()
def __destroy__(): Notify.uninit()
def quit(self, source): if self.timer: self.timer.cancel() notify.uninit() gtk.main_quit()
def connect_clicked(self, does_profile_exist, profile_name): # process a connection request from the user if does_profile_exist is 1: select = self.ap_list.get_selection() network_ssid = self.get_ssid(select) n = Notify.Notification.new( "Found existing profile.", "NetCTL found an existing profile for this network. Connecting to " + network_ssid + " using profile " + profile_name) n.show() net_interface = self.interface_name InterfaceControl.down(self, net_interface) NetCTL.stop_all(self) NetCTL.start(self, profile_name) n = Notify.Notification.new( "Connected to new network!", "You are now connected to " + network_ssid, "dialog-information") n.show() elif does_profile_exist == 0: if self.NoWifiMode == 0: select = self.ap_list.get_selection() network_ssid = self.get_ssid(select) print("nSSID = " + network_ssid) profile = "netgui_" + network_ssid print("profile = " + profile) net_interface = self.interface_name if os.path.isfile(profile_dir + profile): InterfaceControl.down(self, net_interface) NetCTL.stop_all(self) NetCTL.start(profile) n = Notify.Notification.new( "Connected to new network!", "You are now connected to " + network_ssid, "dialog-information") n.show() else: network_security = self.get_security(select) if network_security == "Open": key = "none" else: key = self.get_network_pw() create_config(network_ssid, self.interface_name, network_security, key) try: InterfaceControl.down(self, net_interface) NetCTL.stop_all(self) NetCTL.start(self, profile) n = Notify.Notification.new( "Connected to new network!", "You are now connected to " + network_ssid, "dialog-information") n.show() except Exception as e: n = Notify.Notification.new( "Error!", "There was an error. The error was: " + str(e) + ". Please report an issue at the github page if it persists.", "dialog-information") n.show() Notify.uninit() elif self.NoWifiMode == 1: select = self.ap_list.get_selection() nwm_profile = self.get_ssid(select) net_interface = get_interface() try: InterfaceControl.down(self, net_interface) NetCTL.stop_all(self) NetCTL.start(self, nwm_profile) n = Notify.Notification.new( "Connected to new profile!", "You are now connected to " + nwm_profile, "dialog-information") n.show() except: n = Notify.Notification.new( "Error!", "There was an error. Please report an issue at the " + "github page if it persists.", "dialog-information") n.show() Notify.uninit() self.start_scan(self)
def quit(_): os.system('echo "Laptop-Mode" > /tmp/screen_management/screen_orientation') notify.uninit() gtk.main_quit()
def quit(self, source=None): # send dead signal to tcp server self.send('dead') notify.uninit() Gtk.main_quit()
def terminate(self): self.logger.debug('terminate()') Notify.uninit() Gtk.main_quit() self.logger.debug('Gtk.main_quit() called')
def connectClicked(self, doesProfileExist, profileName): '''process a connection request from the user''' if doesProfileExist is 1: select = self.APList.get_selection() networkSSID = self.getSSID(select) n = Notify.Notification.new( "Found existing profile.", "NetCTL found an existing profile for this network. Connecting to " + networkSSID + " using profile " + profileName) n.show() netinterface = self.interfaceName InterfaceCtl.down(self, netinterface) NetCTL.stopall(self) NetCTL.start(self, profileName) n = Notify.Notification.new( "Connected to new network!", "You are now connected to " + networkSSID, "dialog-information") n.show() elif doesProfileExist == 0: if self.NoWifiMode == 0: select = self.APList.get_selection() networkSSID = self.getSSID(select) print("nSSID = " + networkSSID) profile = "netgui_" + networkSSID print("profile = " + profile) netinterface = self.interfaceName if os.path.isfile(conf_dir + profile): InterfaceCtl.down(self, netinterface) NetCTL.stopall(self) NetCTL.start(profile) n = Notify.Notification.new( "Connected to new network!", "You are now connected to " + networkSSID, "dialog-information") n.show() else: networkSecurity = self.getSecurity(select) key = self.get_network_pw() CreateConfig(networkSSID, self.interfaceName, networkSecurity, key) try: InterfaceCtl.down(self, netinterface) NetCTL.stopall(self) NetCTL.start(self, profile) n = Notify.Notification.new( "Connected to new network!", "You are now connected to " + networkSSID, "dialog-information") n.show() except Exception as e: n = Notify.Notification.new( "Error!", "There was an error. The error was: " + str(e) + ". Please report an issue at the github page if it persists.", "dialog-information") n.show() Notify.uninit() elif self.NoWifiMode == 1: select = self.APList.get_selection() NWMprofile = self.getSSID(select) netinterface = GetInterface() try: InterfaceCtl.down(self, netinterface) NetCTL.stopall(self) NetCTL.start(self, NWMprofile) n = Notify.Notification.new( "Connected to new profile!", "You are now connected to " + NWMprofile, "dialog-information") n.show() except: n = Notify.Notification.new( "Error!", "There was an error. Please report an issue at the github page if it persists.", "dialog-information") n.show() Notify.uninit() self.startScan(self)
def quit(_): notify.uninit() gtk.main_quit()
def quit(self, w=None): notify.uninit() gtk.main_quit()
def change_quit_var(self): #print("yaysdfghjksdfghjkasdfghjklasdfghjk") #global quit_variable config.quit_variable = True notify.uninit()
def uninit(): if available and Notify.is_initted(): logging.info("stopping desktop notifications") _notifications.clear() Notify.uninit()
def __del__(self): Notify.uninit()
class discord_status_dev(GObject.Object, Peas.Activatable): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "settings.json") with open(path) as file: settings = json.load(file) show_notifs = settings["show_notifs"] time_style = settings["time_style"] try: Notify.init("Rhythmbox") except: print("Failed to init Notify. Is the notificaion service running?") is_streaming = False RPC = Presence("589905203533185064") connected = False gave_up = False try: RPC.connect() #try: # if show_notifs: # Notify.Notification.new("Rhythmbox Discord Status Plugin", "Connected to Discord").show() # Notify.uninit() #except: # print("Failed to init Notify. Is the notificaion service running?") connected = True except ConnectionRefusedError: try: if show_notifs: Notify.Notification.new( "Rhythmbox Discord Status Plugin", "Failed to connect to Discord: ConnectionRefused. Is the client open?" ).show() Notify.uninit() except: print("Failed to init Notify. Is the notificaion service running?") if show_notifs: while not connected and not gave_up: dialog = Gtk.Dialog( title="Discord Rhythmbox Status Plugin", parent=None, buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OK, Gtk.ResponseType.OK)) hbox = Gtk.HBox() label = Gtk.Label( "\nFailed to connect to the Discord client. Make sure that it is open. Retry?\n" ) hbox.pack_start(label, True, True, 0) dialog.vbox.pack_start(hbox, True, True, 0) dialog.vbox.show_all() response = dialog.run() if response == Gtk.ResponseType.OK: try: RPC.connect() connected = True except ConnectionRefusedError: print("Failed to retry connection to Discord") elif response == Gtk.ResponseType.CANCEL: gave_up = True dialog.destroy() else: pass dialog.destroy() __gtype_name__ = "DiscordStatusPlugin" object = GObject.property(type=GObject.Object) start_date = None playing_date = None is_playing = False def __init__(self): GObject.Object.__init__(self) def do_activate(self): shell = self.object sp = shell.props.shell_player self.psc_id = sp.connect("playing-song-changed", self.playing_entry_changed) self.pc_id = sp.connect("playing-changed", self.playing_changed) self.ec_id = sp.connect("elapsed-changed", self.elapsed_changed) self.pspc_id = sp.connect("playing-song-property-changed", self.playing_song_property_changed) def do_deactivate(self): shell = self.object sp = shell.props.shell_player sp.disconnect(self.psc_id) sp.disconnect(self.pc_id) sp.disconnect(self.ec_id) sp.disconnect(self.pspc_id) self.RPC.clear(pid=os.getpid()) self.RPC.close() def get_info(self, sp): album = None title = None artist = None duration = None if not sp.get_playing_entry().get_string(RB.RhythmDBPropType.ALBUM): album = "" else: album = " - %s" % (sp.get_playing_entry().get_string( RB.RhythmDBPropType.ALBUM)) if album == " - Unknown": album = "" if not sp.get_playing_entry().get_string(RB.RhythmDBPropType.TITLE): title = "Unknown" else: title = sp.get_playing_entry().get_string( RB.RhythmDBPropType.TITLE) if not sp.get_playing_entry().get_string(RB.RhythmDBPropType.ARTIST): artist = "Unknown" else: artist = sp.get_playing_entry().get_string( RB.RhythmDBPropType.ARTIST) if not sp.get_playing_entry().get_ulong(RB.RhythmDBPropType.DURATION): duration = 0 else: duration = sp.get_playing_entry().get_ulong( RB.RhythmDBPropType.DURATION) return [album, title, artist, duration] def playing_song_property_changed(self, sp, uri, property, old, newvalue): print("playing_song_property_changed: %s %s %s %s" % (uri, property, old, newvalue)) info = self.get_info(sp) album = info[0] title = info[1] artist = info[2] details = "%s%s" % (artist, album) if details == "Unknown": details = title if property == "rb:stream-song-title": self.is_streaming = True self.update_streaming_rpc(details, newvalue) def update_streaming_rpc(self, info, d): if info == "Unknown": self.RPC.update(state=d[0:127], large_image="rhythmbox", small_image="play", small_text="Streaming", start=int(time.time())) return self.RPC.update(state=info[0:127], details=d[0:127], large_image="rhythmbox", small_image="play", small_text="Streaming", start=int(time.time())) def playing_entry_changed(self, sp, entry): if sp.get_playing_entry(): self.start_date = int(time.time()) self.playing_date = self.start_date info = self.get_info(sp) album = info[0] title = info[1] artist = info[2] duration = info[3] details = "%s%s" % (artist, album) if duration == 0: self.update_streaming_rpc(details, title) if duration == 0 and self.is_streaming: return else: self.is_streaming = False self.is_playing = True start_time = int(time.time()) pos = sp.get_playing_time().time end_time = (start_time + duration - pos) if self.time_style == 1 else None self.RPC.update(state=details[0:127], details=title[0:127], large_image="rhythmbox", small_image="play", small_text="Playing", start=start_time, end=end_time) def playing_changed(self, sp, playing): album = None title = None artist = None if sp.get_playing_entry(): info = self.get_info(sp) album = info[0] title = info[1] artist = info[2] duration = info[3] details = "%s%s" % (artist, album) if duration == 0 and not self.is_streaming: self.update_streaming_rpc(details, title) if duration == 0: return else: self.is_streaming = False start_time = int(time.time()) pos = sp.get_playing_time().time end_time = (start_time + duration - pos) if self.time_style == 1 else None if playing: self.is_playing = True self.RPC.update(state=details[0:127], details=title[0:127], large_image="rhythmbox", small_image="play", small_text="Playing", start=start_time, end=end_time) return self.is_playing = False self.RPC.clear(pid=os.getpid()) def elapsed_changed(self, sp, elapsed): if not self.playing_date or not self.is_playing or self.time_style == 0: return else: self.playing_date += 1 if self.playing_date - elapsed == self.start_date: return else: if sp.get_playing_entry() and self.is_playing and not elapsed == 0: self.playing_date = self.start_date + elapsed info = self.get_info(sp) album = info[0] title = info[1] artist = info[2] duration = info[3] details = "%s%s" % (artist, album) if duration == 0 and not self.is_streaming: self.update_streaming_rpc(details, title) if duration == 0: return else: self.is_streaming = False start_time = int(time.time()) pos = sp.get_playing_time().time end_time = (start_time + duration - pos) if self.time_style == 1 else None self.RPC.update(state=details[0:127], details=title[0:127], large_image="rhythmbox", small_image="play", small_text="Playing", start=start_time, end=end_time)
def on_exit(): """ Uninitialize the registered notificaion. """ logging.debug('Stop Notification plugin') Notify.uninit()
while self.timer: if self.stop_timer: self.stop_timer = False return self.timer -= 1 mins, secs = divmod(self.timer, 60) self.timer_lbl.set_label("{:02d}:{:02d}".format(mins, secs)) self.handle_window_stats() sleep(1) self.resolve_state() self.timer_thread = threading.Thread(target=self.countdown) self.timer_thread.daemon = True self.timer_thread.start() def notify(self, notify_event): self.notifs.update("Pydoro", NOTIFICATIONS.get(notify_event)) self.notifs.show() def handle_window_stats(self): self.current_window = self.screen.get_active_window().get_name() self.active_windows[self.current_window] += 1 print(self.active_windows) if __name__ == "__main__": win = Pydoro() win.connect("destroy", Gtk.main_quit) win.show_all() Gtk.main() Notify.uninit()
def uninit(): if available and Notify.is_initted(): if _log.isEnabledFor(_INFO): _log.info("stopping desktop notifications") _notifications.clear() Notify.uninit()
def do_deactivate(self): Notify.uninit() self.shell.props.feed_list.disconnect(self._handler_id)
def quit(self, source): if self.proc: # os.killpg(os.getpgid(self.proc.pid), signal.SIGTERM) self.deactivate(source) Notify.uninit() Gtk.main_quit()
def done(self): self.close() Notify.uninit() Gtk.main_quit()
def onQuit(self, *args): Notify.uninit() Gtk.main_quit()
def finalize(): Notify.uninit() Gtk.main_quit()
def quit(source): notify.uninit() gtk.main_quit()
def quit(self, asdgaf): #print("Raching Here") config.quit_variable = True notify.uninit() gtk.main_quit()
def quit(self): print("Indicator: Quitting.") Notify.uninit()
def __del__(self): self.notifier.close() Notify.uninit()
def on_unload(self): Notify.uninit()
def quit(source): Notify.uninit() Gtk.main_quit()
def close(): Notify.uninit() exit(1)
def quit(self, *args): notify.uninit() gtk.main_quit()
def main(): if os.environ.get('INVOCATION_ID', False): logging.basicConfig(level=logging.INFO, format='[%(levelname)s] %(message)s') else: logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s') config_path = os.path.join(os.environ.get('XDG_CONFIG_HOME', '~/.config'), 'maildirwatch.conf') argv = Gtk.init(sys.argv) epilog = ( 'In addition to these arguments, you can also specify GTK options,\n' 'see man page gtk-options(7) for details.') parser = argparse.ArgumentParser( description=__doc__, epilog=epilog, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument( '-c', '--config', metavar='PATH', help='path to configuration file \n(default {})'.format(config_path), default=config_path) parser.add_argument('-d', '--debug', action='store_true', help='set debug logging level') parser.add_argument('--version', action='version', version='%(prog)s {}'.format(__version__)) args = parser.parse_args(argv[1:]) if args.debug: logger.setLevel(logging.DEBUG) user_config_path = os.path.expanduser(args.config) logger.info('Loading config file %s', user_config_path) config.read(user_config_path) if not Notify.init('maildir-watch'): logger.critical('Could not init Notify') sys.exit(1) else: logger.debug('Notify server info: %s', Notify.get_server_info()) logger.debug('Notify server capabilities: %s', Notify.get_server_caps()) app = App() app.start() success = True try: GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, Gtk.main_quit) def unhandled_exception_hook(etype, value, traceback): logger.exception('Unhandled exception, exiting', exc_info=(etype, value, traceback)) Gtk.main_quit() nonlocal success success = False # Install an unhandled exception handler which stops GTK event loop. sys.excepthook = unhandled_exception_hook Gtk.main() finally: logger.debug('About to exit, cleaning up') app.stop() Notify.uninit() sys.exit(0 if success else 1)
def display_notification(percent): Notify.init("Keyboard backlight changer") kb_light_notify=Notify.Notification.new("Keyboard backlight", "Set to " + str(int(percent)) + "%", "dialog-information") kb_light_notify.set_timeout(3) kb_light_notify.show() Notify.uninit()
def quit(_): set_current_layout() notify.uninit() gtk.main_quit()