Ejemplo n.º 1
0
    def handle(self, message):
        if message.command == "PING":
            # respond quick before we get booted!
            m = Message()
            m.command = "PONG"
            m.params = message.params
            self.connection.send(m)
        elif message.command == "QUIT":
            # user left. Log them out if need be
            u = db.User(nick=message.sender)
            u.logout()
        elif message.command == "NICK":
            # nick updated. Chase them!
            u = db.User(nick=message.sender)
            u.change_nick(message.params[0])
        elif message.command == "PRIVMSG" and message.params[1].startswith(self.settings["command_prefix"]):
            # palm it off to the plugins
            for plugin in self.plugins:
                if plugin.handle(message):
                    break

        channel = None
        if message.params[0].startswith("#"):
            channel = message.params[0]
        db.log_message(message.command, message.sender, channel, " ".join(message.params))
Ejemplo n.º 2
0
# -*- coding: UTF-8 -*-
import logging.config, os, sys
configRoot = os.path.join(os.getcwd(), "resources", "logging.conf")
try:
    logging.config.fileConfig(configRoot)
except:
    logging.basicConfig()
    logging.getLogger('root').exception('Failed to initialize logging... falling back to defaults.')

# Add the lib dir to path  
sys.path.append(os.path.join(os.getcwd(), 'lib'))

#
# There is probably a better way to do this... 
# letmewatchthis is the handler module which registers it's mode/action handler functions with the plugin
# module which then can handle plugin requests from the mode/action handler registry
import letmewatchthis, plugin

log = logging.getLogger("root")
log.info("calling with args: %s" % str(sys.argv))

try:
    plugin.handle()
except:
    log.exception("Failed to handle request")
Ejemplo n.º 3
0
# -*- coding: UTF-8 -*-
import plugin
import logging
import sys

plugin.initialize('plugin.video.primewire', 'primewire')

log = logging.getLogger("root")
log.info("calling with args: %s" % str(sys.argv))

try:
    plugin.handle()
except:
    log.exception("Failed to handle request")
Ejemplo n.º 4
0
	def process(self, path, postmap, **params):
		"""
		Receives all POSTs from device via httpd module.
		This queues updates to listening processes and runs each
		plugin synchonously in order.  Both plugins and processes
		receive the same data. Plugins are passed the data as a dict.
		Processes receive it as netstring-encapsulated JSON (see
		https://en.wikipedia.org/wiki/Netstring).

		The data sent consists of the complete state from the device for all
		known message types.  A top-level tag '_last_element' points at the
		name of the last element that changed, triggering the event.

		Because each event is handled synchronously, all recipients will
		receive all changes in order.  Exceptions to this are:

		-  A maximum number of pending changes is kept for each process
		   so a process that stalls for some period may lose data.

		-  A write error on a process socket causes all the data to be flushed
		   and the connection dropped.	The process will receive the current
		   state when it next connects.
	"""
		if self.is_inet and self.authorized_addrs is not None and 'handler' not in params:
			self.log.error("Missing handler - cannot validate client address")
			return None
		if 'data' not in params:
			self.log.error("Missing payload from device")
			return None
		if self.is_inet and self.authorized_addrs is not None:
			client_ip = netaddr.IPAddress(params['handler'].client_address[0])
			self.log.debug("Checking client address %s", client_ip)
			authorized = False
			for net in self.authorized_addrs:
				if client_ip in net:
					authorized = True
					break
			if not authorized:
				self.log.warning("Unauthorized access from client at %s", client_ip)
				return None
		payload = params['data']
		try:
			dom = xml.dom.minidom.parseString(payload)
		except Exception as e:
			self.log.error("Payload parse failed -- %s", str(e), exc_info=True)
			self.log.error("Failed payload was ...")
			if len(payload) > 1000:
				payload = payload[:1000] + ' ...'
			for line in str(payload).splitlines():
				self.log.error("  ] %s", line)
			return
		self.log.debug("Payload parsed successfully ...")
		for line in dom.toprettyxml(indent="  ").splitlines():
			line = line.rstrip()
			if line:
				self.log.debug("  ] %s", line)

		resp = (200, '', 'text/plain')

		now = time.time()
		for node in dom.getElementsByTagName('rainforest'):
			header = {}
			header['_version'] = node.getAttribute('version')
			header['_mac'] = node.getAttribute('macId')
			rainforest_timestamp = node.getAttribute('timestamp')
			if rainforest_timestamp:
				try:
					header['_timestamp'] = int(rainforest_timestamp.strip('s'))
					self.log.debug("Rainforest %s v%s timestamp delta %.3f",
							header['_mac'], header['_version'], now - header['_timestamp'])
				except Exception as e:
					self.log.warning("Could not load Rainforest timestamp '%s' -- %s",
												rainforest_timestamp, str(e))
					header['_timestamp'] = None
			else:
				self.log.warning("No timestamp in rainforest POST xml")

			if node.nodeType != node.ELEMENT_NODE or not node.hasChildNodes():
				self.log.warning("XML rainforest node had no children")
				continue
			for command in node.childNodes:
				if command.nodeType != command.ELEMENT_NODE:
					continue
				self.log.debug("XML item '%s' has command element '%s'", node.nodeName, command.nodeName)
				info = {}
				raw_info = {}
				props = self.properties.get(command.nodeName, {})
				for elem in command.childNodes:
					if elem.nodeType != elem.ELEMENT_NODE:
						continue
					tag = elem.nodeName
					val = elem.childNodes[0].nodeValue.strip()
					valstr = val
					if self.is_hex.match(val):
						try:
							val = int(val, 0)
							if val > 0x7FFFFFFF:
								val -= 0x100000000
						except:
							pass
					self.log.debug("%s %s = %s", command.nodeName, elem.nodeName, repr(val))
					info[tag] = val
					raw_info[tag] = valstr
				info['_name'] = command.nodeName
				info['_raw'] = raw_info
				info['_timestamp'] = now
				vals = {}
				for reading in props.get('readings', []):
					vals[reading] = self.read_meter(reading, info)
				if 'units' in props:
					vals['_units'] = props['units']
				if len(vals) > 0:
					info['_readings'] = vals
				resp = self.check_schedule(info)
				self.state[command.nodeName] = info
				self.state['_last_element'] = command.nodeName

			self.state['_last_update'] = now
			self.state['_timestamp'] = header['_timestamp']
			for tag in ['_mac', '_version']:
				if header[tag] != self.state.get(tag):
					self.log.info("Rainforest %s value changed from %s to %s",
										tag, repr(self.state.get(tag)), header[tag])
					self.state[tag] = header[tag]
		for plugin, name in self.plugins:
			try:
				self.log.debug("Running plugin '%s' for command '%s'", name, self.state['_last_element'])
				plugin.handle(self)
			except Exception as e:
				self.log.error("Plugin '%s' failed for '%s' -- %s",
							name, self.state['_last_element'], str(e), exc_info=True)
		self.save_state()
		if self.event_set is not None:
			self.event_set.filter(self.state)
		return resp