# Path: pygowave_server/utils.py
# class AlreadyUploadedFile(UploadedFile):
# 	"""
# 	This class is used to mark files, which have already been uploaded and
# 	stored. It still can be opened and read.
# 	
# 	"""
# 	def __init__(self, path, name, size):
# 		super(AlreadyUploadedFile, self).__init__(name, size=size)
# 		self.path = path
# 		self._file = None
# 	
# 	def open(self):
# 		self._file = open(path, "r")
# 		
# 	def seek(self, pos):
# 		if self._file != None:
# 			self._file.seek(pos)
# 	
# 	def tell(self):
# 		if self._file == None: return 0
# 		return self._file.tell()
# 
# 	def read(self, num_bytes=None):
# 		if self._file == None: self.open()
# 		if num_bytes == None:
# 			return self._file.read()
# 		else:
# 			return self._file.read(num_bytes)
# 		
# 	def reset(self):
# 		self._file.reset()
# 
# 	def close(self):
# 		self._file.close()
# 	
# 	def temporary_file_path(self):
# 		"""
# 		Emulate behaviour of temporary uploaded files.
# 		
# 		"""
# 		return self.path
# 
# def get_profile_model():
# 	"""
# 	Return the user profile model class as defined by the AUTH_PROFILE_MODULE
# 	setting. If that setting is missing SiteProfileNotAvailable is raised.
# 	
# 	"""
# 	if not hasattr(settings, 'AUTH_PROFILE_MODULE') or settings.AUTH_PROFILE_MODULE == None:
# 		raise SiteProfileNotAvailable
# 	
# 	profile_mod = get_model(*settings.AUTH_PROFILE_MODULE.split('.'))
# 	if profile_mod is None:
# 		raise SiteProfileNotAvailable
# 	
# 	return profile_mod
# 
# Path: pygowave_server/models.py
# class Gadget(models.Model):
# 	"""
# 	A gadget that has been uploaded or is referenced on this server.
# 	Users can register their gadgets on this server to conveniently add them
# 	to a Wave.
# 	
# 	Note: A uploaded gadget is never deleted from disk as it may be used by
# 	other waves. An exception to this are Gadget marked as "devel" versions.
# 	Those Gadgets can be simply overwritten and thus replace already running
# 	instances.
# 	
# 	"""
# 	
# 	by_user = models.ForeignKey(User, related_name="my_gadgets")
# 	title = models.CharField(max_length=255, unique=True, verbose_name=_(u'Title'))
# 	description = models.CharField(max_length=255, blank=True, verbose_name=_(u'Description'))
# 	url = models.URLField(blank=True, verbose_name=_(u'URL'))
# 	hosted_filename = models.CharField(max_length=255, blank=True, verbose_name=_(u'Hosted filename'))
# 	devel = models.BooleanField(default=False, verbose_name=_(u'Development version'))
# 	
# 	def is_hosted(self):
# 		return len(self.hosted_filename) > 0
# 		
# 	def instantiate(self):
# 		"""
# 		Create a GadgetElement from this Gadget.
# 		
# 		"""
# 		return GadgetElement(url=self.url)
# 	
# 	def __unicode__(self):
# 		return u"Gadget '%s' by '%s'" % (self.title, self.by_user.username)


from django import forms
from django.forms import widgets
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from django.core.files.uploadedfile import UploadedFile
from django.utils.hashcompat import sha_constructor
from random import random
from pygowave_server.utils import AlreadyUploadedFile, get_profile_model
from pygowave_server.models import Gadget
from registration.forms import RegistrationForm
				from PIL import Image
			from lxml.etree import XMLSyntaxError
		from pygowave_server.engine import GadgetLoader
import os, urllib2
	def external_url(self):
		return self.cleaned_data["external"] == 1

	def clean(self):
		if len(self.errors) > 0:
			return self.cleaned_data
		
		if self.external_url():
			url = self.cleaned_data["url"]
		else:
			# Local path
			url = "file://" + settings.GADGET_ROOT + self.cleaned_data["url"].split("/")[-1]
		
		# Check Gadget
		try:
			gadget = GadgetLoader(url)
		except urllib2.HTTPError:
			raise forms.ValidationError(_(u'Gadget could not be downloaded.'))
		except XMLSyntaxError:
			if not self.external_url():
				os.remove(settings.GADGET_ROOT + self.cleaned_data["upload"])
			raise forms.ValidationError(_(u'Gadget quick-check failed: Bad XML format.'))
		except ValueError, e:
			if not self.external_url():
				os.remove(settings.GADGET_ROOT + self.cleaned_data["upload"])
			raise forms.ValidationError(_(u'Gadget quick-check failed: %s.') % (e.args[0]))
		
		return self.cleaned_data
	
	class Meta:

# Path: pygowave_server/utils.py
# class AlreadyUploadedFile(UploadedFile):
# 	"""
# 	This class is used to mark files, which have already been uploaded and
# 	stored. It still can be opened and read.
# 	
# 	"""
# 	def __init__(self, path, name, size):
# 		super(AlreadyUploadedFile, self).__init__(name, size=size)
# 		self.path = path
# 		self._file = None
# 	
# 	def open(self):
# 		self._file = open(path, "r")
# 		
# 	def seek(self, pos):
# 		if self._file != None:
# 			self._file.seek(pos)
# 	
# 	def tell(self):
# 		if self._file == None: return 0
# 		return self._file.tell()
# 
# 	def read(self, num_bytes=None):
# 		if self._file == None: self.open()
# 		if num_bytes == None:
# 			return self._file.read()
# 		else:
# 			return self._file.read(num_bytes)
# 		
# 	def reset(self):
# 		self._file.reset()
# 
# 	def close(self):
# 		self._file.close()
# 	
# 	def temporary_file_path(self):
# 		"""
# 		Emulate behaviour of temporary uploaded files.
# 		
# 		"""
# 		return self.path
# 
# def get_profile_model():
# 	"""
# 	Return the user profile model class as defined by the AUTH_PROFILE_MODULE
# 	setting. If that setting is missing SiteProfileNotAvailable is raised.
# 	
# 	"""
# 	if not hasattr(settings, 'AUTH_PROFILE_MODULE') or settings.AUTH_PROFILE_MODULE == None:
# 		raise SiteProfileNotAvailable
# 	
# 	profile_mod = get_model(*settings.AUTH_PROFILE_MODULE.split('.'))
# 	if profile_mod is None:
# 		raise SiteProfileNotAvailable
# 	
# 	return profile_mod
# 
# Path: pygowave_server/models.py
# class Gadget(models.Model):
# 	"""
# 	A gadget that has been uploaded or is referenced on this server.
# 	Users can register their gadgets on this server to conveniently add them
# 	to a Wave.
# 	
# 	Note: A uploaded gadget is never deleted from disk as it may be used by
# 	other waves. An exception to this are Gadget marked as "devel" versions.
# 	Those Gadgets can be simply overwritten and thus replace already running
# 	instances.
# 	
# 	"""
# 	
# 	by_user = models.ForeignKey(User, related_name="my_gadgets")
# 	title = models.CharField(max_length=255, unique=True, verbose_name=_(u'Title'))
# 	description = models.CharField(max_length=255, blank=True, verbose_name=_(u'Description'))
# 	url = models.URLField(blank=True, verbose_name=_(u'URL'))
# 	hosted_filename = models.CharField(max_length=255, blank=True, verbose_name=_(u'Hosted filename'))
# 	devel = models.BooleanField(default=False, verbose_name=_(u'Development version'))
# 	
# 	def is_hosted(self):
# 		return len(self.hosted_filename) > 0
# 		
# 	def instantiate(self):
# 		"""
# 		Create a GadgetElement from this Gadget.
# 		
# 		"""
# 		return GadgetElement(url=self.url)
# 	
# 	def __unicode__(self):
# 		return u"Gadget '%s' by '%s'" % (self.title, self.by_user.username)


# Path: pygowave_server/forms.py
from django import forms
from django.forms import widgets
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from django.core.files.uploadedfile import UploadedFile
from django.utils.hashcompat import sha_constructor
from random import random
from pygowave_server.utils import AlreadyUploadedFile, get_profile_model
from pygowave_server.models import Gadget
from registration.forms import RegistrationForm
				from PIL import Image
			from lxml.etree import XMLSyntaxError
		from pygowave_server.engine import GadgetLoader
import os, urllib2

	def external_url(self):
		return self.cleaned_data["external"] == 1

	def clean(self):
		if len(self.errors) > 0:
			return self.cleaned_data
		
		if self.external_url():
			url = self.cleaned_data["url"]
		else:
			# Local path
			url = "file://" + settings.GADGET_ROOT + self.cleaned_data["url"].split("/")[-1]
		
		# Check Gadget
		try:
			gadget = GadgetLoader(url)
		except urllib2.HTTPError:
			raise forms.ValidationError(_(u'Gadget could not be downloaded.'))
		except XMLSyntaxError:
			if not self.external_url():
				os.remove(settings.GADGET_ROOT + self.cleaned_data["upload"])
			raise forms.ValidationError(_(u'Gadget quick-check failed: Bad XML format.'))
		except ValueError, e:
			if not self.external_url():
				os.remove(settings.GADGET_ROOT + self.cleaned_data["upload"])
			raise forms.ValidationError(_(u'Gadget quick-check failed: %s.') % (e.args[0]))
		
		return self.cleaned_data
	
	class Meta:

		model = Gadget