Esempio n. 1
0
def main(cfg):
	game = cfg.get("game")

	old_streams = []
	old_streams_channel_ids = []

	new_streams = []

	# Stream IDs change each time the stream is started so we actually use the
	# channel ID instead as this won't change
	current_streams = get_current_streams(game)
	current_streams_channel_ids = [stream["channel"]["_id"] for stream in current_streams]
	logging.debug("current_streams_channel_ids: {0}".format(current_streams_channel_ids))

	# Read in the previous list of streams
	cache_dir = xdg.BaseDirectory.save_cache_path("twitchwatch")
	cache_file = os.path.join(cache_dir, "streams.json")

	# Get the old list of streams and give it to current list to save
	stream_cache = read_stream_cache(cache_file)

	if current_streams:
		if game in stream_cache.keys():
			old_streams = stream_cache.get(game)

			# Get the list of channel ids for old streams
			old_streams_channel_ids = [stream["channel"]["_id"] for stream in old_streams]

			logging.debug("old_streams_channel_ids: {0}".format(old_streams_channel_ids))

			# Iterate through the list of current streams
			for stream in current_streams:
				channel_id = stream["channel"]["_id"]

				# We want to make sure old_stream is very old (more than max_age hours ago)
				if channel_id not in old_streams_channel_ids:
					new_streams.append(stream)
		else:
			new_streams = current_streams

		if new_streams:
			# Are configured to use a socket file for broadcasting?
			if "socket" in cfg:
				try:
					sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
					server_address = cfg["socket"]

					try:
						logging.debug("Talking to socket file {0}".format(server_address))
						sock.connect(server_address)
					except Exception as e:
						logging.error("Could not connect to socket file {0}".format(server_address))
						logging.exception(e)
						return

					message = json.dumps(new_streams)
					message_bytes = bytes(message, "utf-8")

					logging.debug("Sending '%s'" % message)

					sock.sendall(message_bytes)
				except Exception as e:
					logging.exception(e)
				finally:
					sock.close()

	if current_streams_channel_ids != old_streams_channel_ids:
		stream_cache[game] = current_streams
		save_stream_cache(cache_file, stream_cache)