#python module to control eMule
#Copyright (C) 2005  sambarza@tin.it

#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

import re, traceback, sys

class TagNotFound(Exception):
	def __init__(self, tag):
		self.tag = tag
	
	def __str__(self):
		return self.tag

#-------------------------------------------
# Parse_xml
#-------------------------------------------
def parse_xml(xml_data, tag):
	""" Search a tag in a xml text """
	
	result = re.search('<'+tag+'[^>]*>(.*?)</'+tag+'>', xml_data, re.DOTALL)
	
	if not result:
		raise TagNotFound(tag)
	
	return result.group(1)

#-------------------------------------------
# find_all
#-------------------------------------------
def find_all(xml_data, tag):
	
	result = re.findall('<'+tag+'[^>]*>(.*?)</'+tag+'>', xml_data)
	
	if not result:
		raise TagNotFound(tag)
	
	return result
	
def print_trace():
	traceback.print_exc(file=sys.stdout)
	
def decode(text):
	try:
		new_text = text
		new_text = new_text.replace("\\n", "\n")
		new_text = new_text.replace("&#8217;", "'")
		new_text = new_text.replace("&amp;", "&")
		# Uff... what's a difficul... replace "\\" with "\"
		new_text = new_text.replace("\\\\", u"\u005C")
	except:
		pass
	
	return new_text
