Exemple #1
0
    def _send(self, type, packet):
        """Send the GNTP Packet"""

        data = packet.encode()

        logger.debug('To : %s:%s <%s>\n%s', self.hostname, self.port,
                     packet.__class__, data)

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(self.socketTimeout)
        s.connect((self.hostname, self.port))
        s.send(data.encode('utf8', 'replace'))
        recv_data = s.recv(1024)
        while not recv_data.endswith("\r\n\r\n"):
            recv_data += s.recv(1024)
        response = gntp.parse_gntp(recv_data)
        s.close()

        logger.debug('From : %s:%s <%s>\n%s', self.hostname, self.port,
                     response.__class__, response)

        if response.info['messagetype'] == '-OK':
            return True
        logger.error('Invalid response: %s', response.error())
        return response.error()
Exemple #2
0
 def ProcessPacket( self, packet ):
     ''' 
     Processes a packet
     @param: packet     The packet to process
     '''
     try:
         message = gntp.parse_gntp( packet, self.server.password )
     except:
         logging.exception('Failed to parse packet:\n%s' % packet )
         return
     if message:
         remoteAddress = self.transport.getPeer()
         logging.debug( 
                 'From %s:%s <%s>\n%s',
                 remoteAddress.host,
                 remoteAddress.port,
                 message.__class__,
                 message 
                 )
         resp = self.server.GetResponse( 
                 message, 
                 IpEndpoint( remoteAddress.host, remoteAddress.port ) 
                 )
         data = resp.encode()
         self.transport.write( data.encode('utf-8', 'replace') )
Exemple #3
0
    def _send(self, messagetype, packet):
        """Send the GNTP Packet"""

        packet.validate()
        data = packet.encode()

        #logger.debug('To : %s:%s <%s>\n%s', self.hostname, self.port, packet.__class__, data)
        #Less verbose
        logger.debug('To : %s:%s <%s>', self.hostname, self.port,
                     packet.__class__)

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(self.socketTimeout)
        s.connect((self.hostname, self.port))
        s.send(data)
        recv_data = s.recv(1024)
        while not recv_data.endswith("\r\n\r\n"):
            recv_data += s.recv(1024)
        response = gntp.parse_gntp(recv_data)
        s.close()

        #logger.debug('From : %s:%s <%s>\n%s', self.hostname, self.port, response.__class__, response)
        #Less verbose
        logger.debug('From : %s:%s <%s>', self.hostname, self.port,
                     response.__class__)

        if type(response) == gntp.GNTPOK:
            return True
        if response.error()[0] == '404' and 'disabled' in response.error()[1]:
            # Ignore message saying that user has disabled this class
            return True
        logger.error('Invalid response: %s', response.error())
        return response.error()
Exemple #4
0
    def handle(self):
        self.hostaddr, self.port = self.request.getsockname()
        logger.info('Handling request from %s:%s', self.hostaddr, self.port)

        self.data = self.read()

        try:
            message = gntp.parse_gntp(self.data, self.server.options.password)

            response = gntp.GNTPOK(action=message.info['messagetype'])
            add_origin_info(response)

            if message.info['messagetype'] == 'NOTICE':
                response.add_header('Notification-ID', '')
            elif message.info['messagetype'] == 'SUBSCRIBE':
                response.add_header('Subscription-TTL', '10')

            self.write(response.encode())
        except GNTPError:
            logger.exception('GNTP Error')
            return
        except:
            logger.exception('Unknown Error')
            return

        if self.server.options.debug:
            logger.info('Reloading bridges')
            self.server.notifiers = load_bridges(self.server.config)

        for bridge in self.server.notifiers:
            bridge(message, self.hostaddr, self.port)
Exemple #5
0
def on_growl_data(data):
    gmsg = e = None
    for password in common.pref("gntp.password_list", type=list,
                                default=[]) + [None]:
        try:
            gmsg = gntp.parse_gntp(data, password)
        except gntp.BaseError as e:
            continue
        else:
            e = None
            break
    else:
        if e is not None:
            raise e

    headers = {}
    for key, value in gmsg.headers.items():
        #        value_chunks = email.Header.decode_header(value)
        #        value = ''.join(chunk.decode(charset) for (chunk, charset) in value_chunks)
        headers[key.lower()] = value.decode('utf8')

    on_growl_message(
        util.Storage(info=gmsg.info, headers=headers,
                     resources=gmsg.resources))

    return str(gntp.GNTPOK(action=gmsg.info['messagetype']))
Exemple #6
0
	def _send(self, messagetype, packet):
		"""Send the GNTP Packet"""

		packet.validate()
		data = packet.encode()

		#logger.debug('To : %s:%s <%s>\n%s', self.hostname, self.port, packet.__class__, data)
		#Less verbose
		logger.debug('To : %s:%s <%s>', self.hostname, self.port, packet.__class__)

		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.settimeout(self.socketTimeout)
		s.connect((self.hostname, self.port))
		s.send(data)
		recv_data = s.recv(1024)
		while not recv_data.endswith("\r\n\r\n"):
			recv_data += s.recv(1024)
		response = gntp.parse_gntp(recv_data)
		s.close()

		#logger.debug('From : %s:%s <%s>\n%s', self.hostname, self.port, response.__class__, response)
		#Less verbose
		logger.debug('From : %s:%s <%s>', self.hostname, self.port, response.__class__)

		if type(response) == gntp.GNTPOK:
			return True
		if response.error()[0] == '404' and 'disabled' in response.error()[1]:
			# Ignore message saying that user has disabled this class
			return True
		logger.error('Invalid response: %s', response.error())
		return response.error()
def sendGNTPMessage(message,addr):
    import gntp
    response = gntp.parse_gntp(sendMessage(message.encode(), addr, socket.SOCK_STREAM,1024))

    if isinstance(response, gntp.GNTPOK):
        return response

    raise Exception('invalid response\n', response)
Exemple #8
0
def _send(host,port,data,debug=False):
	if debug: print '<Sending>\n',data,'\n</Sending>'
	
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.connect((host,port))
	s.send(data)
	response = gntp.parse_gntp(s.recv(1024))
	s.close()
	
	if debug: print '<Recieved>\n',response,'\n</Recieved>'
Exemple #9
0
	def _send(self, type, data):
		"""Send the GNTP Packet"""
		logger.debug('To : %s:%s <%s>\n%s', self.hostname, self.port, type, data)

		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.connect((self.hostname, self.port))
		s.send(data.encode('utf8', 'replace'))
		response = gntp.parse_gntp(s.recv(1024))
		s.close()

		logger.debug('From : %s:%s <%s>\n%s', self.hostname, self.port, response.__class__, response)
		return response
Exemple #10
0
    def _send(host, port, data, debug=False):
        if debug:
            print('<Sending>\n', data, '\n</Sending>')

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((host, port))
        s.send(data)
        response = gntp.parse_gntp(s.recv(1024))
        s.close()

        if debug:
            print('<Received>\n', response, '\n</Received>')

        return response
Exemple #11
0
    def _send(self, type, data):
        """Send the GNTP Packet"""
        logger.debug('To : %s:%s <%s>\n%s', self.hostname, self.port, type,
                     data)

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((self.hostname, self.port))
        s.send(data.encode('utf8', 'replace'))
        response = gntp.parse_gntp(s.recv(1024))
        s.close()

        logger.debug('From : %s:%s <%s>\n%s', self.hostname, self.port,
                     response.__class__, response)
        return response
Exemple #12
0
	def send(self,type,data):
		'''
		Send the GNTP Packet
		'''
		if self.debug:
			print 'To: %s:%s <%s>'%(self.hostname,self.port,type)
			print '<Sending>\n',data,'\n</Sending>'
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.connect((self.hostname,self.port))
		s.send(data)
		response = gntp.parse_gntp(s.recv(1024))
		s.close()
		if self.debug:
			print 'From: %s:%s <%s>'%(self.hostname,self.port,response.__class__)
			print '<Recieved>\n',response,'\n</Recieved>'
		return response
Exemple #13
0
 def Recv(self):
     """
     Receives a growl packet
     @returns        A gntp class representing the received data
     """
     data = self.socket.recv( 1024 )
     while not data.endswith( '\r\n\r\n' ):
         data += self.socket.recv( 1024 )
     message = gntp.parse_gntp( data, self.password )
     if message:
         remoteAddress = self.socket.getsockname()
         logging.debug( 
                 'From %s:%s <%s>\n%s',
                 remoteAddress[0],
                 remoteAddress[1],
                 message.__class__,
                 message 
                 )
     return message
Exemple #14
0
	def _send(self, type, data):
		"""Send the GNTP Packet"""
		#logger.debug('To : %s:%s <%s>\n%s', self.hostname, self.port, type, data)
		#Less verbose please
		logger.debug('To : %s:%s <%s>', self.hostname, self.port, type)

		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.connect((self.hostname, self.port))
		s.send(data.encode('utf8', 'replace'))
		try:
			s.settimeout(10)
		except:
			pass
		response = gntp.parse_gntp(s.recv(1024))
		s.close()

		#logger.debug('From : %s:%s <%s>\n%s', self.hostname, self.port, response.__class__, response)
		#Less verbose please
		logger.debug('From : %s:%s <%s>', self.hostname, self.port, response.__class__)

		return response
Exemple #15
0
	def _send(self, type, packet):
		"""Send the GNTP Packet"""

		data = packet.encode()

		logger.debug('To : %s:%s <%s>\n%s', self.hostname, self.port, packet.__class__, data)

		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.connect((self.hostname, self.port))
		s.send(data.encode('utf8', 'replace'))
		recv_data = s.recv(1024)
		while not recv_data.endswith("\r\n\r\n"):
			recv_data += s.recv(1024)
		response = gntp.parse_gntp(recv_data)
		s.close()

		logger.debug('From : %s:%s <%s>\n%s', self.hostname, self.port, response.__class__, response)

		if response.info['messagetype'] == '-OK':
			return True
		logger.error('Invalid response: %s', response.error())
		return response.error()
Exemple #16
0
    def _send(self, type, data):
        """Send the GNTP Packet"""
        #logger.debug('To : %s:%s <%s>\n%s', self.hostname, self.port, type, data)
        #Less verbose please
        logger.debug('To : %s:%s <%s>', self.hostname, self.port, type)

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((self.hostname, self.port))
        s.send(data.encode('utf8', 'replace'))
        try:
            s.settimeout(10)
        except:
            pass
        response = gntp.parse_gntp(s.recv(1024))
        s.close()

        #logger.debug('From : %s:%s <%s>\n%s', self.hostname, self.port, response.__class__, response)
        #Less verbose please
        logger.debug('From : %s:%s <%s>', self.hostname, self.port,
                     response.__class__)

        return response
Exemple #17
0
def on_growl_data(data):
    gmsg = e = None
    for password in common.pref("gntp.password_list", type=list, default = []) + [None]:
        try:
            gmsg = gntp.parse_gntp(data, password)
        except gntp.BaseError as e:
            continue
        else:
            e = None
            break
    else:
        if e is not None:
            raise e

    headers = {}
    for key, value in gmsg.headers.items():
#        value_chunks = email.Header.decode_header(value)
#        value = ''.join(chunk.decode(charset) for (chunk, charset) in value_chunks)
        headers[key.lower()] = value.decode('utf8')

    on_growl_message(util.Storage(info = gmsg.info, headers = headers, resources = gmsg.resources))

    return str(gntp.GNTPOK(action = gmsg.info['messagetype']))
Exemple #18
0
	def _send(self, messagetype, packet):
		"""Send the GNTP Packet"""

		packet.validate()
		data = packet.encode()

		logger.debug('To : %s:%s <%s>\n%s', self.hostname, self.port, packet.__class__, data)

		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.settimeout(self.socketTimeout)
		s.connect((self.hostname, self.port))
		s.send(data)
		recv_data = s.recv(1024)
		while not recv_data.endswith("\r\n\r\n"):
			recv_data += s.recv(1024)
		response = gntp.parse_gntp(recv_data)
		s.close()

		logger.debug('From : %s:%s <%s>\n%s', self.hostname, self.port, response.__class__, response)

		if type(response) == gntp.GNTPOK:
			return True
		logger.error('Invalid response: %s', response.error())
		return response.error()
Exemple #19
0
        logger.debug('To : %s:%s <%s>\n%s', self.hostname, self.port,
                     packet.__class__, data)

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(self.socketTimeout)
        try:
            s.connect((self.hostname, self.port))
            s.send(data)
            recv_data = s.recv(1024)
            while not recv_data.endswith("\r\n\r\n"):
                recv_data += s.recv(1024)
        except socket.error, e:
            raise errors.NetworkError(e.message)

        response = gntp.parse_gntp(recv_data)
        s.close()

        logger.debug('From : %s:%s <%s>\n%s', self.hostname, self.port,
                     response.__class__, response)

        if type(response) == gntp.GNTPOK:
            return True
        logger.error('Invalid response: %s', response.error())
        return response.error()


def mini(description,
         applicationName='PythonMini',
         noteType="Message",
         title="Mini Message",
Exemple #20
0
        data = packet.encode()

        logger.debug('To : %s:%s <%s>\n%s', self.hostname, self.port, packet.__class__, data)

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(self.socketTimeout)
        try:
            s.connect((self.hostname, self.port))
            s.send(data)
            recv_data = s.recv(1024)
            while not recv_data.endswith("\r\n\r\n"):
                recv_data += s.recv(1024)
        except socket.error, e:
            raise errors.NetworkError(e.message)

        response = gntp.parse_gntp(recv_data)
        s.close()

        logger.debug('From : %s:%s <%s>\n%s', self.hostname, self.port, response.__class__, response)

        if type(response) == gntp.GNTPOK:
            return True
        logger.error('Invalid response: %s', response.error())
        return response.error()


def mini(description, applicationName='PythonMini', noteType="Message",
            title="Mini Message", applicationIcon=None, hostname='localhost',
            password=None, port=23053, sticky=False, priority=None,
            callback=None, notificationIcon=None, identifier=None,
            notifierFactory=GrowlNotifier):
Exemple #21
0
class GrowlNotifier(object):
    """Helper class to simplfy sending Growl messages

    :param string applicationName: Sending application name
    :param list notification: List of valid notifications
    :param list defaultNotifications: List of notifications that should be enabled
        by default
    :param string applicationIcon: Icon URL
    :param string hostname: Remote host
    :param integer port: Remote port
    """

    passwordHash = 'MD5'
    socketTimeout = 3

    def __init__(self,
                 applicationName='Python GNTP',
                 notifications=[],
                 defaultNotifications=None,
                 applicationIcon=None,
                 hostname='localhost',
                 password=None,
                 port=23053):

        self.applicationName = applicationName
        self.notifications = list(notifications)
        if defaultNotifications:
            self.defaultNotifications = list(defaultNotifications)
        else:
            self.defaultNotifications = self.notifications
        self.applicationIcon = applicationIcon

        self.password = password
        self.hostname = hostname
        self.port = int(port)

    def _checkIcon(self, data):
        '''
        Check the icon to see if it's valid

        If it's a simple URL icon, then we return True. If it's a data icon
        then we return False
        '''
        logger.info('Checking icon')
        return data.startswith('http')

    def register(self):
        """Send GNTP Registration

        .. warning::
            Before sending notifications to Growl, you need to have
            sent a registration message at least once
        """
        logger.info('Sending registration to %s:%s', self.hostname, self.port)
        register = gntp.GNTPRegister()
        register.add_header('Application-Name', self.applicationName)
        for notification in self.notifications:
            enabled = notification in self.defaultNotifications
            register.add_notification(notification, enabled)
        if self.applicationIcon:
            if self._checkIcon(self.applicationIcon):
                register.add_header('Application-Icon', self.applicationIcon)
            else:
                id = register.add_resource(self.applicationIcon)
                register.add_header('Application-Icon', id)
        if self.password:
            register.set_password(self.password, self.passwordHash)
        self.add_origin_info(register)
        self.register_hook(register)
        return self._send('register', register)

    def notify(self,
               noteType,
               title,
               description,
               icon=None,
               sticky=False,
               priority=None,
               callback=None,
               identifier=None,
               custom={}):
        """Send a GNTP notifications

        .. warning::
            Must have registered with growl beforehand or messages will be ignored

        :param string noteType: One of the notification names registered earlier
        :param string title: Notification title (usually displayed on the notification)
        :param string description: The main content of the notification
        :param string icon: Icon URL path
        :param boolean sticky: Sticky notification
        :param integer priority: Message priority level from -2 to 2
        :param string callback:  URL callback
        :param dict custom: Custom attributes. Key names should be prefixed with X-
            according to the spec but this is not enforced by this class

        .. warning::
            For now, only URL callbacks are supported. In the future, the
            callback argument will also support a function
        """
        logger.info('Sending notification [%s] to %s:%s', noteType,
                    self.hostname, self.port)
        assert noteType in self.notifications
        notice = gntp.GNTPNotice()
        notice.add_header('Application-Name', self.applicationName)
        notice.add_header('Notification-Name', noteType)
        notice.add_header('Notification-Title', title)
        if self.password:
            notice.set_password(self.password, self.passwordHash)
        if sticky:
            notice.add_header('Notification-Sticky', sticky)
        if priority:
            notice.add_header('Notification-Priority', priority)
        if icon:
            if self._checkIcon(icon):
                notice.add_header('Notification-Icon', icon)
            else:
                id = notice.add_resource(icon)
                notice.add_header('Notification-Icon', id)

        if description:
            notice.add_header('Notification-Text', description)
        if callback:
            notice.add_header('Notification-Callback-Target', callback)
        if identifier:
            notice.add_header('Notification-Coalescing-ID', identifier)

        for key in custom:
            notice.add_header(key, custom[key])

        self.add_origin_info(notice)
        self.notify_hook(notice)

        return self._send('notify', notice)

    def subscribe(self, id, name, port):
        """Send a Subscribe request to a remote machine"""
        sub = gntp.GNTPSubscribe()
        sub.add_header('Subscriber-ID', id)
        sub.add_header('Subscriber-Name', name)
        sub.add_header('Subscriber-Port', port)
        if self.password:
            sub.set_password(self.password, self.passwordHash)

        self.add_origin_info(sub)
        self.subscribe_hook(sub)

        return self._send('subscribe', sub)

    def add_origin_info(self, packet):
        """Add optional Origin headers to message"""
        packet.add_header('Origin-Machine-Name', platform.node())
        packet.add_header('Origin-Software-Name', 'gntp.py')
        packet.add_header('Origin-Software-Version', __version__)
        packet.add_header('Origin-Platform-Name', platform.system())
        packet.add_header('Origin-Platform-Version', platform.platform())

    def register_hook(self, packet):
        pass

    def notify_hook(self, packet):
        pass

    def subscribe_hook(self, packet):
        pass

    def _send(self, messagetype, packet):
        """Send the GNTP Packet"""

        packet.validate()
        data = packet.encode()

        logger.debug('To : %s:%s <%s>\n%s', self.hostname, self.port,
                     packet.__class__, data)

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(self.socketTimeout)
        try:
            s.connect((self.hostname, self.port))
            s.send(data)
            recv_data = s.recv(1024)
            while not recv_data.endswith("\r\n\r\n"):
                recv_data += s.recv(1024)
            #except socket.error, e:
        except socket.error, e:
            print socket
            print e
            raise errors.NetworkError(e)

        response = gntp.parse_gntp(recv_data)
        s.close()

        logger.debug('From : %s:%s <%s>\n%s', self.hostname, self.port,
                     response.__class__, response)

        if type(response) == gntp.GNTPOK:
            return True
        logger.error('Invalid response: %s', response.error())
        return response.error()