def register_growl(growl_server, growl_password): """ Register this app with Growl """ error = None host, port = split_host(growl_server or '') sys_name = hostname(host) # Clean up persistent data in GNTP to make re-registration work GNTPRegister.notifications = [] GNTPRegister.headers = {} growler = GrowlNotifier( applicationName='SABnzbd%s' % sys_name, applicationIcon=get_icon(), notifications=[Tx(NOTIFICATION[key]) for key in NOTIFY_KEYS], hostname=host or 'localhost', port=port or 23053, password=growl_password or None ) try: ret = growler.register() if ret is None or isinstance(ret, bool): logging.info('Registered with Growl') ret = growler else: error = 'Cannot register with Growl %s' % str(ret) logging.debug(error) del growler ret = None except socket.error, err: error = 'Cannot register with Growl %s' % str(err) logging.debug(error) del growler ret = None
def main(): '''Sets up WeeChat Growl notifications.''' # Initialize options. for option, value in SETTINGS.items(): if not weechat.config_is_set_plugin(option): weechat.config_set_plugin(option, value) # Initialize Growl. name = "WeeChat" hostname = weechat.config_get_plugin('hostname') password = weechat.config_get_plugin('password') icon_path = os.path.join(weechat.info_get("weechat_dir", ""), weechat.config_get_plugin('icon')) try: icon = open(icon_path, "rb").read() except IOError: weechat.prnt('', 'Weechat-Growl: {0} could not be opened. '.format(icon_path) + 'Please make sure it exists.') icon = None notifications = [ 'Public', 'Private', 'Action', 'Notice', 'Invite', 'Highlight', 'Server', 'Channel', 'DCC', 'WeeChat' ] if len(hostname) == 0: hostname = '' if len(password) == 0: password = '' growl = GrowlNotifier( applicationName=name, hostname=hostname, password=password, notifications=notifications, applicationIcon=icon) try: growl.register() except Exception as error: weechat.prnt('', 'growl: {0}'.format(error)) STATE['growl'] = growl STATE['icon'] = icon # Register hooks. weechat.hook_signal( 'irc_server_connected', 'cb_irc_server_connected', '') weechat.hook_signal( 'irc_server_disconnected', 'cb_irc_server_disconnected', '') weechat.hook_signal('upgrade_ended', 'cb_upgrade_ended', '') weechat.hook_print('', '', '', 1, 'cb_process_message', '')
class TestHash(unittest.TestCase): def setUp(self): self.growl = GrowlNotifier("GNTP unittest", ["Testing"]) self.growl.register() def test_lines(self): for priority in [2, 1, 0, -1, -2]: msg = "Priority %s" % priority self.growl.notify("Testing", msg, msg, priority=priority)
class TestHash(unittest.TestCase): def setUp(self): self.growl = GrowlNotifier('GNTP unittest', ['Testing']) self.growl.register() def test_lines(self): for priority in [2, 1, 0, -1, -2]: msg = 'Priority %s' % priority self.growl.notify('Testing', msg, msg, priority=priority)
class TestHash(unittest.TestCase): def setUp(self): self.growl = GrowlNotifier('GNTP unittest', ['Testing']) self.growl.register() self.dir = os.path.dirname(__file__) self.file = os.path.join(self.dir, 'test_lines.txt') def test_lines(self): for line in open(self.file): self.growl.notify('Testing', 'Line', line)
class Notifier(object): def __init__(self, app_name="autocheck"): self.growl = GrowlNotifier( applicationName=app_name, notifications=["New Message"], defaultNotifications=["New Message"] ) self.growl.register() def notify(self, title, description, kind="pass", sticky=False): icon = open(join(dirname(__file__), "images", kind + ".png"), "rb").read() self.growl.notify(noteType="New Message", title=title, description=description, icon=icon, sticky=sticky)
class ConfigTests(GNTPTestCase): def setUp(self): if os.path.exists(ORIGINAL_CONFIG): os.rename(ORIGINAL_CONFIG, BACKUP_CONFIG) self.growl = GrowlNotifier(self.application, [self.notification_name]) self.growl.register() def test_missing_config(self): self.assertIsTrue(self._notify(description='No config file test')) def tearDown(self): if os.path.exists(BACKUP_CONFIG): os.rename(BACKUP_CONFIG, ORIGINAL_CONFIG)
def __init__(self): self.base_url = 'http://stackoverflow.com/questions/tagged/' self.get_or_create_database() self.growl = GrowlNotifier( applicationName='StackOverflowChecker', notifications=['new'], ) self.growl.register() self.tags = [('django', True), ('python', False)] self.get_questions() self.close_connection()
class Notifier(object): def __init__(self, app_name='autorestart'): self.growl = GrowlNotifier(applicationName=app_name, notifications=['New Message'], defaultNotifications=['New Message']) self.growl.register() def notify(self, title, description, sticky=False): self.growl.notify( noteType='New Message', title=title, description=description, sticky=sticky, )
def register_growl(growl_server, growl_password): """ Register this app with Growl """ error = None host, port = split_host(growl_server or '') sys_name = hostname(host) # Reduce logging of Growl in Debug/Info mode logging.getLogger('gntp').setLevel(logging.WARNING) # Clean up persistent data in GNTP to make re-registration work GNTPRegister.notifications = [] GNTPRegister.headers = {} growler = GrowlNotifier( applicationName='SABnzbd%s' % sys_name, applicationIcon=get_icon(), notifications=[Tx(NOTIFICATION[key]) for key in NOTIFY_KEYS], hostname=host or 'localhost', port=port or 23053, password=growl_password or None ) try: ret = growler.register() if ret is None or isinstance(ret, bool): logging.info('Registered with Growl') ret = growler else: error = 'Cannot register with Growl %s' % str(ret) logging.debug(error) del growler ret = None except (gntp.errors.NetworkError, gntp.errors.AuthError) as err: error = 'Cannot register with Growl %s' % str(err) logging.debug(error) del growler ret = None except: error = 'Unknown Growl registration error' logging.debug(error) logging.info("Traceback: ", exc_info=True) del growler ret = None return ret, error
class Notifier(object): def __init__(self, app_name='autocheck'): self.growl = GrowlNotifier(applicationName=app_name, notifications=['New Message'], defaultNotifications=['New Message']) self.growl.register() def notify(self, title, description, kind='pass', sticky=False): icon = open(join(dirname(__file__), 'images', kind + '.png'), 'rb').read() self.growl.notify( noteType='New Message', title=title, description=description, icon=icon, sticky=sticky, )
class TestHash(unittest.TestCase): def setUp(self): self.growl = GrowlNotifier('GNTP unittest', ['Testing']) self.growl.register() def test_english(self): self.growl.notify('Testing','Testing','Hello') def test_extra(self): self.growl.notify('Testing','Testing','allô') def test_japanese(self): self.growl.notify('Testing','Testing',u'おはおう')
def growlInit(self): # addr = (self.config['growl_host'], self.config['growl_port']) # s = socket(AF_INET,SOCK_DGRAM) # p = GrowlRegistrationPacket("Deluge", self.config['growl_password']) # p.addNotification("Download Completed", True) # p.addNotification("Torrent Added", True) # s.sendto(p.payload(), addr) # s.close() self.growl = GrowlNotifier( applicationName="Deluge", notifications=["Torrent Added", "Download Completed"], defaultNotifications=["Torrent Added"], hostname=self.config['growl_host'], password=self.config['growl_password'], port=self.config['growl_port'], debug=0) result = self.growl.register()
def bark(message, host, password): growl = GrowlNotifier( applicationName = NAME, notifications = [NOTIFIER], defaultNotifications = [NOTIFIER], hostname = host, port = '23053', password = password ) growl.register() growl.notify( noteType = NOTIFIER, title = TITLE, description = message, icon = ICON_URL, sticky = False, priority = 1, )
def main(): """Sets up WeeChat Growl notifications.""" # Initialize options. for option, value in SETTINGS.items(): if not weechat.config_is_set_plugin(option): weechat.config_set_plugin(option, value) # Initialize Growl. name = "WeeChat" hostname = weechat.config_get_plugin("hostname") password = weechat.config_get_plugin("password") icon = "file://{0}".format(os.path.join(weechat.info_get("weechat_dir", ""), weechat.config_get_plugin("icon"))) notifications = [ "Public", "Private", "Action", "Notice", "Invite", "Highlight", "Server", "Channel", "DCC", "WeeChat", ] if len(hostname) == 0: hostname = "" if len(password) == 0: password = "" growl = GrowlNotifier( applicationName=name, hostname=hostname, password=password, notifications=notifications, applicationIcon=icon ) try: growl.register() except Exception as error: weechat.prnt("", "growl: {0}".format(error)) STATE["growl"] = growl STATE["icon"] = icon # Register hooks. weechat.hook_signal("irc_server_connected", "cb_irc_server_connected", "") weechat.hook_signal("irc_server_disconnected", "cb_irc_server_disconnected", "") weechat.hook_signal("upgrade_ended", "cb_upgrade_ended", "") weechat.hook_print("", "", "", 1, "cb_process_message", "")
def __init__(self): self.base_url = 'http://stackoverflow.com/questions/tagged/' self.get_or_create_database() self.growl = GrowlNotifier( applicationName='StackOverflowChecker', notifications=['new'],) self.growl.register() self.tags = [('django', True), ('python', False)] self.get_questions() self.close_connection()
def register_growl(): """ Register this app with Growl """ error = None host, port = sabnzbd.misc.split_host(sabnzbd.cfg.growl_server()) if host: sys_name = '@' + sabnzbd.misc.hostname().lower() else: sys_name = '' # Clean up persistent data in GNTP to make re-registration work GNTPRegister.notifications = [] GNTPRegister.headers = {} growler = GrowlNotifier( applicationName = 'SABnzbd%s' % sys_name, applicationIcon = get_icon(host or None), notifications = [Tx(_NOTIFICATION[key]) for key in _KEYS], hostname = host or None, port = port or 23053, password = sabnzbd.cfg.growl_password() or None ) try: ret = growler.register() if ret is None or isinstance(ret, bool): logging.info('Registered with Growl') ret = growler else: error = 'Cannot register with Growl %s' % str(ret) logging.debug(error) del growler ret = None except socket.error, err: error = 'Cannot register with Growl %s' % str(err) logging.debug(error) del growler ret = None
def main(): (options, message) = ClientParser().parse_args() logging.basicConfig(level=options.verbose) if not os.path.exists(DEFAULT_CONFIG): logging.info('No config read found at %s', DEFAULT_CONFIG) growl = GrowlNotifier( applicationName=options.app, notifications=[options.name], defaultNotifications=[options.name], hostname=options.host, password=options.password, port=options.port, ) result = growl.register() if result is not True: exit(result) # This would likely be better placed within the growl notifier # class but until I make _checkIcon smarter this is "easier" if options.icon and growl._checkIcon(options.icon) is False: logging.info('Loading image %s', options.icon) f = open(options.icon, 'rb') options.icon = f.read() f.close() result = growl.notify( noteType=options.name, title=options.title, description=message, icon=options.icon, sticky=options.sticky, priority=options.priority, callback=options.callback, identifier=options.identifier, ) if result is not True: exit(result)
def main(): (options, message) = ClientParser().parse_args() logging.basicConfig(level=options.verbose) if not os.path.exists(DEFAULT_CONFIG): logging.info('No config read found at %s', DEFAULT_CONFIG) growl = GrowlNotifier( applicationName=options.app, notifications=[options.name], defaultNotifications=[options.name], hostname=options.host, password=options.password, port=options.port, ) result = growl.register() if result is not True: exit(result) # This would likely be better placed within the growl notifier # class but until I make _checkIcon smarter this is "easier" if options.icon is not None and not options.icon.startswith('http'): logging.info('Loading image %s', options.icon) f = open(options.icon) options.icon = f.read() f.close() result = growl.notify( noteType=options.name, title=options.title, description=message, icon=options.icon, sticky=options.sticky, priority=options.priority, callback=options.callback, identifier=options.identifier, ) if result is not True: exit(result)
def register_growl(): """ Register this app with Growl """ error = None host, port = sabnzbd.misc.split_host(sabnzbd.cfg.growl_server()) if host: sys_name = '@' + sabnzbd.misc.hostname().lower() else: sys_name = '' # Clean up persistent data in GNTP to make re-registration work GNTPRegister.notifications = [] GNTPRegister.headers = {} growler = GrowlNotifier( applicationName='SABnzbd%s' % sys_name, applicationIcon=get_icon(host or None), notifications=[Tx(_NOTIFICATION[key]) for key in _KEYS], hostname=host or None, port=port or 23053, password=sabnzbd.cfg.growl_password() or None) try: ret = growler.register() if ret is None or isinstance(ret, bool): logging.info('Registered with Growl') ret = growler else: error = 'Cannot register with Growl %s' % str(ret) logging.debug(error) del growler ret = None except socket.error, err: error = 'Cannot register with Growl %s' % str(err) logging.debug(error) del growler ret = None
def send_gntp_notification(self): growl_ips = self.growl_ips gntp_ips = self.gntp_ips # don't send to gntp if we can use growl gntp_ips = [ip for ip in gntp_ips if (ip not in growl_ips)] for ip in gntp_ips: growl = GrowlNotifier( applicationName = 'Doorbell', notifications = ['doorbell'], defaultNotifications = ['doorbell'], hostname = ip, password = self.password, ) result = growl.register() if not result: continue result = growl.notify( noteType = 'doorbell', title = self.title, description = self.description, sticky = True, )
def send_gntp_notification(self): growl_ips = self.growl_ips gntp_ips = self.gntp_ips # don't send to gntp if we can use growl gntp_ips = [ip for ip in gntp_ips if (ip not in growl_ips)] for ip in gntp_ips: growl = GrowlNotifier( applicationName='Doorbell', notifications=['doorbell'], defaultNotifications=['doorbell'], hostname=ip, password=self.password, ) result = growl.register() if not result: continue result = growl.notify( noteType='doorbell', title=self.title, description=self.description, sticky=True, )
def main(): (options, message) = ClientParser().parse_args() logging.basicConfig(level=options.verbose) growl = GrowlNotifier( applicationName=options.app, notifications=[options.name], defaultNotifications=[options.name], hostname=options.host, password=options.password, port=options.port, ) result = growl.register() if result is not True: exit(result) # This would likely be better placed within the growl notifier # class but until I make _checkIcon smarter this is "easier" if options.icon is not None and not options.icon.startswith("http"): logging.info("Loading image %s", options.icon) f = open(options.icon) options.icon = f.read() f.close() result = growl.notify( noteType=options.name, title=options.title, description=message, icon=options.icon, sticky=options.sticky, priority=options.priority, callback=options.callback, identifier=options.identifier, ) if result is not True: exit(result)
def test_client(config, options): logging.basicConfig(level=options.verbose) notifier = GrowlNotifier(hostname=config.get('regrowl.server', 'hostname', '127.0.0.1'), port=config.getint('regrowl.server', 'port'), password=config.get('regrowl.server', 'password'), notifications=['Test']) if options.test in ['registration', 'all']: notifier.register() if options.test in ['notification', 'all']: notifier.notify( noteType='Test', title='Testing', description='ReGrowl Test', ) if options.test in ['subscription', 'all']: notifier.subscribe( 'TestId', 'TestName', 1337, )
def forward(self, packet): messagetype = packet.info['messagetype'] for label, settings in self.config.items(__name__): dest, password = settings.split(',') try: host, port = dest.split(':') except ValueError: host, port = dest, DEFAULTS['port'] passwordHash = self.get('passwordHash', DEFAULTS['passwordHash']) packet.set_password(password, passwordHash) logger.info('Forwarding %s to %s:%s', messagetype, host, port) GrowlNotifier( hostname=host, port=port, )._send(messagetype, packet)
def growlInit(self): # addr = (self.config['growl_host'], self.config['growl_port']) # s = socket(AF_INET,SOCK_DGRAM) # p = GrowlRegistrationPacket("Deluge", self.config['growl_password']) # p.addNotification("Download Completed", True) # p.addNotification("Torrent Added", True) # s.sendto(p.payload(), addr) # s.close() self.growl = GrowlNotifier( applicationName = "Deluge", notifications = ["Torrent Added", "Download Completed"], defaultNotifications = ["Torrent Added"], hostname = self.config['growl_host'], password = self.config['growl_password'], port = self.config['growl_port'], debug = 0 ) result = self.growl.register()
def bark(message, host, password): growl = GrowlNotifier(applicationName=NAME, notifications=[NOTIFIER], defaultNotifications=[NOTIFIER], hostname=host, port='23053', password=password) growl.register() growl.notify( noteType=NOTIFIER, title=TITLE, description=message, icon=ICON_URL, sticky=False, priority=1, )
def test_client(config, options): logging.basicConfig(level=options.verbose) notifier = GrowlNotifier( hostname=config.get('regrowl.server', 'hostname', '127.0.0.1'), port=config.getint('regrowl.server', 'port'), password=config.get('regrowl.server', 'password'), notifications=['Test'] ) if options.test in ['registration', 'all']: notifier.register() if options.test in ['notification', 'all']: notifier.notify( noteType='Test', title='Testing', description='ReGrowl Test', ) if options.test in ['subscription', 'all']: notifier.subscribe( 'TestId', 'TestName', 1337, )
event = argv[1] # Last.fm network network = pylast.LastFMNetwork(api_key = API_KEY, api_secret = API_SECRET, username = USERNAME, password_hash = pylast.md5(PASSWORD)) # Stores Pianobar information. info = {} # Initalize a new Growl object (localhost does not require a password). growl = GrowlNotifier( applicationName=u'Pianobar', notifications=[ u'Song Start', u'Song End', u'Song Love', u'Song Ban', u'Song Shelve', u'Song Bookmark', u'Artist Bookmark', u'Program Error', u'Network Error']) # Register Pianobar with Growl. try: growl.register() except socket.error: # Be silent. pass # Parse stdin into the dictionary. for line in sys.stdin:
def setUp(self): self.growl = GrowlNotifier("GNTP unittest", ["Testing"]) self.growl.register()
def setUp(self): self.growl = GrowlNotifier('GNTP unittest', ['Testing']) self.growl.register()
def __init__(self, app_name="autocheck"): self.growl = GrowlNotifier( applicationName=app_name, notifications=["New Message"], defaultNotifications=["New Message"] ) self.growl.register()
icon='http://www.reddit.com/static/spreddit2.gif', sticky=True, callback=url[:url.find('.json')], priority=2, ) print 'Updated!' if __name__ == '__main__': if len(sys.argv) < 2: print "Error: requires url to monitor" os.exit(1) url = sys.argv[1] growl = GrowlNotifier( applicationName='Monitor', notifications=['Updated'], ) growl.register() last_hash = None while True: try: last_hash = update(url, last_hash=last_hash, callback=my_callback) except Exception as e: print e # jitter our updates sleep(randint(interval-5, interval+5))
dest='password', default=None) self.add_option('-A','--appname', help='GNTP Application Name', dest='app', default=APPLICATION_NAME) self.add_option('-v',dest='debug', help='Print Debugging to stderr', action='store_true', default=False) if __name__ == "__main__": signal.signal(signal.SIGINT, signal_exit) parser = Parser() (options, args) = parser.parse_args() growl = GrowlNotifier( applicationName = options.app, notifications = [NOTIFICATION_NAME], hostname = options.host, password = options.password, port = options.port, debug = options.debug, ) growl.register() while( True ): line = sys.stdin.readline() if not line: break sys.stdout.write(line) growl.notify(NOTIFICATION_NAME,NOTIFICATION_NAME,line)
def setUp(self): self.growl = GrowlNotifier('GNTP unittest', ['Testing']) self.growl.register() self.dir = os.path.dirname(__file__) self.file = os.path.join(self.dir, 'test_lines.txt')
# If we still have an empty title, use the # first bit of the message as the title if values.title == '': values.title = message[:20] return values, message if __name__ == "__main__": (options, message) = ClientParser('~/.gntp').parse_args() growl = GrowlNotifier( applicationName=options.app, notifications=[options.name], defaultNotifications=[options.name], hostname=options.host, password=options.password, port=options.port, debug=options.debug, ) result = growl.register() if result is not True: exit(result) result = growl.notify( noteType=options.name, title=options.title, description=message, icon=options.icon, sticky=options.sticky, priority=options.priority, )
# -*- coding: utf-8 -*- # Simple script to test sending UTF8 text with the GrowlNotifier class import logging logging.basicConfig(level=logging.DEBUG) from gntp.notifier import GrowlNotifier import platform growl = GrowlNotifier(notifications=['Testing'],password='******',hostname='ayu') growl.subscribe(platform.node(),platform.node(),12345)
# If we still have an empty title, use the # first bit of the message as the title if values.title == '': values.title = message[:20] return values, message if __name__ == "__main__": (options,message) = ClientParser('~/.gntp').parse_args() growl = GrowlNotifier( applicationName = options.app, notifications = [options.name], defaultNotifications = [options.name], hostname = options.host, password = options.password, port = options.port, debug = options.debug, ) result = growl.register() if result is not True: exit(result) result = growl.notify( noteType = options.name, title = options.title, description = message, icon = options.icon, sticky = options.sticky, priority = options.priority, )
import sys # Script Arguments argv = os.sys.argv argc = len(argv) # Stores Pianobar information. info = {} # Initalize a new Growl object (localhost does not require a password). growl = GrowlNotifier( applicationName=u'Pianobar', notifications=[ u'Song Start', u'Song End', u'Song Love', u'Song Ban', u'Song Shelve', u'Song Bookmark', u'Artist Bookmark', u'Program Error', u'Network Error']) # Register Pianobar with Growl. try: growl.register() except socket.error: # Be silent. pass # Parse stdin into the dictionary. for line in sys.stdin:
def __init__(self, priority=GrowlPriority.NORMAL, version=2, **kwargs): """ Initialize Growl Object """ super(NotifyGrowl, self).__init__(title_maxlen=250, body_maxlen=32768, image_size=GROWL_IMAGE_XY, notify_format=NotifyFormat.TEXT, **kwargs) # A Global flag that tracks registration self.is_registered = False if not self.port: self.port = GROWL_UDP_PORT # The Priority of the message if priority not in GROWL_PRIORITIES: self.priority = GrowlPriority.NORMAL else: self.priority = priority # Always default the sticky flag to False self.sticky = False # Store Version self.version = version payload = { 'applicationName': self.app_id, 'notifications': [ GROWL_NOTIFICATION_TYPE, ], 'defaultNotifications': [ GROWL_NOTIFICATION_TYPE, ], 'hostname': self.host, 'port': self.port, } if self.password is not None: payload['password'] = self.password self.logger.debug('Growl Registration Payload: %s' % str(payload)) self.growl = GrowlNotifier(**payload) try: self.growl.register() # Toggle our flag self.is_registered = True self.logger.debug( 'Growl server registration completed successfully.') except GrowlNetworkError: self.logger.warning( 'A network error occured sending Growl ' + \ 'notification to %s.' % ( self.host, )) return except GrowlAuthenticationError: self.logger.warning( 'An authentication error occured sending Growl ' + \ 'notification to %s.' % ( self.host, )) return return
class StackOverflowFetcher: def __init__(self): self.base_url = 'http://stackoverflow.com/questions/tagged/' self.get_or_create_database() self.growl = GrowlNotifier( applicationName='StackOverflowChecker', notifications=['new'],) self.growl.register() self.tags = [('django', True), ('python', False)] self.get_questions() self.close_connection() def get_questions(self): """ Parse target URL for new questions. """ while self.tags: tag, sticky = self.tags.pop() url = self.base_url + tag html = urllib2.urlopen(url).read() soup = BeautifulSoup.BeautifulSoup(html) questions = soup.findAll('h3') for question in questions: element = question.find('a') link = element.get('href') question = element.text if self.is_new_link(link): self.growl.notify( noteType = "new", title = question, description = question, icon = "http://example.com/icon.png", sticky = sticky, priority = 1, callback = 'http://stackoverflow.com{0}'.format(link), ) self.record_question(link, question) def get_or_create_database(self): """ Check if database file exists. Create if not. Open file and send query. If query fails, create tables. """ path = os.path.join(os.path.dirname(__file__), 'questions.db') try: f = open(path) except IOError: f = open(path, 'w') f.close() self.conn = sqlite3.connect(path) try: self.conn.execute('SELECT * from questions') except sqlite3.OperationalError: self.create_database() def create_database(self): self.conn.execute('CREATE TABLE questions(link VARCHAR(400), text VARCHAR(300));') def is_new_link(self, link): results = self.conn.execute('SELECT * FROM questions WHERE questions.link = "%s";' % link).fetchall() if not results: return True return False def record_question(self, link, question): results = self.conn.execute('INSERT INTO questions(link, text) VALUES ("%s", "%s");' % (link, question)) def close_connection(self): self.conn.commit() self.conn.close()
class NotifyGrowl(NotifyBase): """ A wrapper to Growl Notifications """ def __init__(self, priority=GrowlPriority.NORMAL, version=2, **kwargs): """ Initialize Growl Object """ super(NotifyGrowl, self).__init__(title_maxlen=250, body_maxlen=32768, image_size=GROWL_IMAGE_XY, notify_format=NotifyFormat.TEXT, **kwargs) # A Global flag that tracks registration self.is_registered = False if not self.port: self.port = GROWL_UDP_PORT # The Priority of the message if priority not in GROWL_PRIORITIES: self.priority = GrowlPriority.NORMAL else: self.priority = priority # Always default the sticky flag to False self.sticky = False # Store Version self.version = version payload = { 'applicationName': self.app_id, 'notifications': [ GROWL_NOTIFICATION_TYPE, ], 'defaultNotifications': [ GROWL_NOTIFICATION_TYPE, ], 'hostname': self.host, 'port': self.port, } if self.password is not None: payload['password'] = self.password self.logger.debug('Growl Registration Payload: %s' % str(payload)) self.growl = GrowlNotifier(**payload) try: self.growl.register() # Toggle our flag self.is_registered = True self.logger.debug( 'Growl server registration completed successfully.') except GrowlNetworkError: self.logger.warning( 'A network error occured sending Growl ' + \ 'notification to %s.' % ( self.host, )) return except GrowlAuthenticationError: self.logger.warning( 'An authentication error occured sending Growl ' + \ 'notification to %s.' % ( self.host, )) return return def _notify(self, title, body, notify_type, **kwargs): """ Perform Growl Notification """ if not self.is_registered: # We can't do anything return None icon = None if self.include_image: if self.version >= 2: # URL Based icon = self.image_url(notify_type) else: # Raw icon = self.image_raw(notify_type) payload = { 'noteType': GROWL_NOTIFICATION_TYPE, 'title': title, 'description': body, 'icon': icon is not None, 'sticky': False, 'priority': self.priority, } self.logger.debug('Growl Payload: %s' % str(payload)) # Update icon of payload to be raw data payload['icon'] = icon try: response = self.growl.notify(**payload) if not isinstance(response, bool): self.logger.warning( 'Growl notification failed to send with response: %s' % \ str(response), ) else: self.logger.debug('Growl notification sent successfully.') except GrowlNetworkError as e: # Since Growl servers listen for UDP broadcasts, # it's possible that you will never get to this part # of the code since there is no acknowledgement as to # whether it accepted what was sent to it or not. # however, if the host/server is unavailable, you will # get to this point of the code. self.logger.warning( 'A Connection error occured sending Growl ' + \ 'notification to %s.' % ( self.host, )) self.logger.debug('Growl Exception: %s' % str(e)) # Return; we're done return False return True
########NEW FILE######## __FILENAME__ = attributes #!/usr/bin/env python # Simple manual test to make sure that attributes do not # accumulate in the base classes # https://github.com/kfdm/gntp/issues/10 import gntp import gntp.notifier a = gntp.notifier.GrowlNotifier(notifications=['A']) b = gntp.notifier.GrowlNotifier(notifications=['B']) a.notify('A','A','A',sticky=True) b.notify('B','B','B') ########NEW FILE######## __FILENAME__ = subscribe # -*- coding: utf-8 -*- # Simple script to test sending UTF8 text with the GrowlNotifier class import logging logging.basicConfig(level=logging.DEBUG) from gntp.notifier import GrowlNotifier import platform growl = GrowlNotifier(notifications=['Testing'],password='******',hostname='ayu') growl.subscribe(platform.node(),platform.node(),12345) ########NEW FILE########
class StackOverflowFetcher: def __init__(self): self.base_url = 'http://stackoverflow.com/questions/tagged/' self.get_or_create_database() self.growl = GrowlNotifier( applicationName='StackOverflowChecker', notifications=['new'], ) self.growl.register() self.tags = [('django', True), ('python', False)] self.get_questions() self.close_connection() def get_questions(self): """ Parse target URL for new questions. """ while self.tags: tag, sticky = self.tags.pop() url = self.base_url + tag html = urllib2.urlopen(url).read() soup = BeautifulSoup.BeautifulSoup(html) questions = soup.findAll('h3') for question in questions: element = question.find('a') link = element.get('href') question = element.text if self.is_new_link(link): self.growl.notify( noteType="new", title=question, description=question, icon="http://example.com/icon.png", sticky=sticky, priority=1, callback='http://stackoverflow.com{0}'.format(link), ) self.record_question(link, question) def get_or_create_database(self): """ Check if database file exists. Create if not. Open file and send query. If query fails, create tables. """ path = os.path.join(os.path.dirname(__file__), 'questions.db') try: f = open(path) except IOError: f = open(path, 'w') f.close() self.conn = sqlite3.connect(path) try: self.conn.execute('SELECT * from questions') except sqlite3.OperationalError: self.create_database() def create_database(self): self.conn.execute( 'CREATE TABLE questions(link VARCHAR(400), text VARCHAR(300));') def is_new_link(self, link): results = self.conn.execute( 'SELECT * FROM questions WHERE questions.link = "%s";' % link).fetchall() if not results: return True return False def record_question(self, link, question): results = self.conn.execute( 'INSERT INTO questions(link, text) VALUES ("%s", "%s");' % (link, question)) def close_connection(self): self.conn.commit() self.conn.close()
class Core(CorePluginBase): def growlInit(self): # addr = (self.config['growl_host'], self.config['growl_port']) # s = socket(AF_INET,SOCK_DGRAM) # p = GrowlRegistrationPacket("Deluge", self.config['growl_password']) # p.addNotification("Download Completed", True) # p.addNotification("Torrent Added", True) # s.sendto(p.payload(), addr) # s.close() self.growl = GrowlNotifier( applicationName = "Deluge", notifications = ["Torrent Added", "Download Completed"], defaultNotifications = ["Torrent Added"], hostname = self.config['growl_host'], password = self.config['growl_password'], port = self.config['growl_port'], debug = 0 ) result = self.growl.register() def sendGrowl(self, noteType, title, description, sticky=False, priority=0): # p = GrowlNotificationPacket(application="Deluge", notification=noteType, title=title, description=description, priority=priority, sticky=sticky, password=self.config['growl_password']); # addr = (self.config['growl_host'], self.config['growl_port']) # s = socket(AF_INET,SOCK_DGRAM) # s.sendto(p.payload(), addr) # s.close() result = self.growl.notify( noteType = noteType, title = title, description = description, icon = '', sticky = sticky, priority = priority ) def enable(self): self.config = deluge.configmanager.ConfigManager("growl.conf", DEFAULT_PREFS) self.growlInit() #component.get("AlertManager").register_handler("torrent_finished_alert", self.on_torrent_finished) d = defer.Deferred() # simulate a delayed result by asking the reactor to schedule # gotResults in 2 seconds time reactor.callLater(2, self.connect_events) log.debug("Growl core plugin enabled!") return d def disable(self): log.debug("Growl core plugin disabled!") #component.get("AlertManager").deregister_handler(self.on_alert_torrent_finished) self.disconnect_events(); self.config.save() def update(self): pass def connect_events(self): event_manager = component.get("EventManager") event_manager.register_event_handler("TorrentFinishedEvent", self.on_torrent_finished) event_manager.register_event_handler("TorrentAddedEvent", self.on_torrent_added) def disconnect_events(self): event_manager = component.get("EventManager") event_manager.deregister_event_handler("TorrentFinishedEvent", self.on_torrent_finished) event_manager.deregister_event_handler("TorrentAddedEvent", self.on_torrent_added) def on_torrent_added(self, torrent_id): if (self.config['growl_torrent_added'] == False): return try: #torrent_id = str(alert.handle.info_hash()) torrent = component.get("TorrentManager")[torrent_id] torrent_status = torrent.get_status({}) message = _("Added Torrent \"%(name)s\"") % torrent_status d = defer.maybeDeferred(self.sendGrowl, "Torrent Added", "Torrent Added", message, self.config['growl_sticky'], self.config['growl_priority']) #d.addCallback(self._on_notify_sucess, 'email') #d.addErrback(self._on_notify_failure, 'email') return d except Exception, e: log.error("error in alert %s" % e)
def __init__(self, app_name='autocheck'): self.growl = GrowlNotifier(applicationName=app_name, notifications=['New Message'], defaultNotifications=['New Message']) self.growl.register()
class Core(CorePluginBase): def growlInit(self): # addr = (self.config['growl_host'], self.config['growl_port']) # s = socket(AF_INET,SOCK_DGRAM) # p = GrowlRegistrationPacket("Deluge", self.config['growl_password']) # p.addNotification("Download Completed", True) # p.addNotification("Torrent Added", True) # s.sendto(p.payload(), addr) # s.close() self.growl = GrowlNotifier( applicationName="Deluge", notifications=["Torrent Added", "Download Completed"], defaultNotifications=["Torrent Added"], hostname=self.config['growl_host'], password=self.config['growl_password'], port=self.config['growl_port'], debug=0) result = self.growl.register() def sendGrowl(self, noteType, title, description, sticky=False, priority=0): # p = GrowlNotificationPacket(application="Deluge", notification=noteType, title=title, description=description, priority=priority, sticky=sticky, password=self.config['growl_password']); # addr = (self.config['growl_host'], self.config['growl_port']) # s = socket(AF_INET,SOCK_DGRAM) # s.sendto(p.payload(), addr) # s.close() result = self.growl.notify(noteType=noteType, title=title, description=description, icon='', sticky=sticky, priority=priority) def enable(self): self.config = deluge.configmanager.ConfigManager( "growl.conf", DEFAULT_PREFS) self.growlInit() #component.get("AlertManager").register_handler("torrent_finished_alert", self.on_torrent_finished) d = defer.Deferred() # simulate a delayed result by asking the reactor to schedule # gotResults in 2 seconds time reactor.callLater(2, self.connect_events) log.debug("Growl core plugin enabled!") return d def disable(self): log.debug("Growl core plugin disabled!") #component.get("AlertManager").deregister_handler(self.on_alert_torrent_finished) self.disconnect_events() self.config.save() def update(self): pass def connect_events(self): event_manager = component.get("EventManager") event_manager.register_event_handler("TorrentFinishedEvent", self.on_torrent_finished) event_manager.register_event_handler("TorrentAddedEvent", self.on_torrent_added) def disconnect_events(self): event_manager = component.get("EventManager") event_manager.deregister_event_handler("TorrentFinishedEvent", self.on_torrent_finished) event_manager.deregister_event_handler("TorrentAddedEvent", self.on_torrent_added) def on_torrent_added(self, torrent_id): if (self.config['growl_torrent_added'] == False): return try: #torrent_id = str(alert.handle.info_hash()) torrent = component.get("TorrentManager")[torrent_id] torrent_status = torrent.get_status({}) message = _("Added Torrent \"%(name)s\"") % torrent_status d = defer.maybeDeferred(self.sendGrowl, "Torrent Added", "Torrent Added", message, self.config['growl_sticky'], self.config['growl_priority']) #d.addCallback(self._on_notify_sucess, 'email') #d.addErrback(self._on_notify_failure, 'email') return d except Exception, e: log.error("error in alert %s" % e)
def setUp(self): if os.path.exists(ORIGINAL_CONFIG): os.rename(ORIGINAL_CONFIG, BACKUP_CONFIG) self.growl = GrowlNotifier(self.application, [self.notification_name]) self.growl.register()