Esempio n. 1
0
def publish(request):
	login = request.POST['login']
	user = authenticate(username=login, password=request.POST['password'])

	if 'wml' in request.GET:
		def error_response(title, error, **kwargs):
			return wml_error_response(title, error)
	else:
		def error_response(title, error, **kwargs):
			dict = {'errorType':title, 'errorDesc':error, 'loginVal':login}
			for k in kwargs.keys(): dict[k] = kwargs[k]
			return render_to_response('addons/publishForm.html', dict)

	if user is None:
		logger.info("Attempt to login as %s from %s failed during publication"
			% (login, request.META['REMOTE_ADDR']))
		return error_response("Authentication error", "Login and/or password incorrect", errors_credentials=True);

	errors_wml = False

	try:
		file_wml = request.FILES['wml']
	except:
		file_wml = None

	cs = CampaignClient()
	if file_wml != None:
		file_data = file_wml.read().encode('ascii', 'ignore')
	else:
		if 'wml' not in request.POST:
			#print 'debug: error no wml file data'
			logger.info("Attempt to publish an addon by %s from %s failed: no WML"
				% (login, request.META['REMOTE_ADDR']))
			return error_response('File error', ['No WML file data'], errors_pbl=True)
		file_data = request.POST['wml'].encode('ascii', 'ignore')

	try:
		decoded_wml = cs.decode(file_data)
	except Exception as e:
		#print "wml decoding error: ", e
		return error_response('File error', ['WML decoding error'], errors_pbl=True)

	keys_vals = {}
	for k in ["title", "author", "description", "version", "icon", "type"]:
		keys_vals[k] = decoded_wml.get_text_val(k)
		if not keys_vals[k] is None:
			keys_vals[k] = keys_vals[k].strip()
		if keys_vals[k] is None or len(keys_vals[k]) < 1:
			#print 'debug: WML key error (PBL IN WML)'
			return error_response('WML key error', 'Mandatory key %s missing' % k)

	try:
		addon_type = AddonType.objects.get(type_name=keys_vals['type'])
	except ObjectDoesNotExist:
		return error_response('WML PBL error', ['Addon has a wrong type'], errors_pbl=True)

	try:
		addon = Addon.objects.get(name=keys_vals['title'])
		if len(addon.authors.filter(name=login)) == 0:
			return error_response('Author error', ['This user is not one of authors'], errors_author=True)
		addon.uploads += 1
	except ObjectDoesNotExist:
		addon = Addon()
		addon.name = keys_vals['title']
		addon.uploads = 1
		addon.downloads = 0

	if addon.file_tbz:
		addon.file_tbz.delete()
	if addon.file_wml:
		addon.file_wml.delete()
	if file_wml != None:
		file_wml.name = addon.name + '.wml'
	else:
		file = open(os.path.join(MEDIA_ROOT, "addons/") + addon.name + ".wml", 'wb')
		file.write(file_data)
		file.close()
		file_wml =  "addons/" + addon.name + ".wml"

	tmp_dir_name = "%016x" % random.getrandbits(128)
	cs.unpackdir(decoded_wml, tmp_dir_name, verbose = False)
	tarname = os.path.join(MEDIA_ROOT, "addons/") + addon.name + ".tar.bz2"
	#print "tar ", "cjf ", tarname, " -C ", tmp_dir_name, ' .'
	Popen(["tar", "cjf", tarname, "-C", tmp_dir_name, '.']).wait()
	shutil.rmtree(tmp_dir_name, True)
	addon.file_tbz = "addons/" + addon.name + ".tar.bz2"
	
	addon.ver = keys_vals['version']
	addon.img = keys_vals['icon']
	
	icon_path = addon.img.split('/')
	current_path = ICONS_ROOT
	i = 0
	while i<len(icon_path) - 1:
		current_path = os.path.join(current_path, icon_path[i])
		i = i + 1
		if not os.path.exists(current_path):
			os.makedirs(current_path)
	
	if not os.path.exists(ICONS_ROOT):
		os.makedirs(ICONS_ROOT)
	shutil.copyfile(icons_dir + addon.img, ICONS_ROOT + addon.img)
	addon.desc = keys_vals['description']
	addon.type = addon_type
	addon.file_wml = file_wml
	addon.lastUpdate = datetime.now()

	addon.save() #needed to avoid a "'Addon' instance needs to have a primary key 
	             # value before a many-to-many relationship can be used." error
	addon.authors.clear()
	authors = keys_vals['author'].split(",")
	if login not in authors:
		authors.append(login)
	for a in authors:
		try:
			author = Author.objects.get(name=a)
		except ObjectDoesNotExist: #todo
			author = Author(name=a)
			author.save()
		addon.authors.add(author)

	addon.save()
	logger.info("User %s from %s has successfully published addon #%d (%s)"
		% (login, request.META['REMOTE_ADDR'], addon.id, addon.name))
	if ('wml' in request.GET):
		return wml_message_response('Success', 'Addon published successfully')
	else:
		return render_to_response('addons/publishForm.html',
			{'publish_success' : True, 'loginVal' : login, 'addonId' : addon.id})
Esempio n. 2
0
def publish(request):
	login = username=request.POST['login']
	user = authenticate(username=login, password=request.POST['password'])

	if user is None:	
		logger.info(	"Attempt to login as " + login +
				" from " + request.META['REMOTE_ADDR'] +
				" failed during an attempt to publish.")

		return render_to_response('addons/publishForm.html', {'errors_credentials' : True,
									'loginVal' : login})

	errors_pbl = False
	errors_wml = False
	file_wml = None
	file_pbl = None
	try:
		file_pbl = request.FILES['pbl']
	except:
		errors_pbl = True
	try:
		file_wml = request.FILES['wml']
	except:
		errors_wml = True

	if errors_wml and errors_pbl:
		logger.info(	"Attempt to publish an addon by " + login +
				" from " + request.META['REMOTE_ADDR'] + 
				" failed due to invalid files.")
		return render_to_response('addons/publishForm.html', {'errors_wml' : errors_wml,
								      'errors_pbl' : errors_pbl,
							              'loginVal' : login})

	def error_response(title, error):
		return render_to_response('addons/error.html',
					  {'errorType':title, 'errorDesc':error})

	keys_vals = {}
	if file_pbl != None:
		try:
			keys_vals = check_pbl(file_pbl.readlines())
		except Exception as inst:
			return error_response('Pbl error', [inst.args[0]])

		try:
			addon_type = AddonType.objects.get(type_name=keys_vals['type'])
		except ObjectDoesNotExist:
			return error_response('PBL error', ['Addon has a wrong type'])

		try:
			addon = Addon.objects.get(name=keys_vals['title'])
			if len(addon.authors.filter(name=login)) == 0:
				return error_response('Author error', ['This user is not one of authors'])
		except ObjectDoesNotExist:
			pass

	if file_pbl and ('wml' not in request.POST or request.POST['wml'] == '') and file_wml == None:
		raise Exception("PBL VERIFICATION FINISHED SUCCESSFUL")

	cs = CampaignClient()
	if file_wml != None:
		file_data = file_wml.read()
	else:
		if 'wml' not in request.POST:
			raise Exception("NO WML FILE DATA")
		file_data = request.POST['wml']
	
	decoded_wml = cs.decode(file_data)

  	for field in ["title", "author", "description", "version", "icon", "type"]:
		keys_vals[field] = decoded_wml.get_text_val(field)
		if keys_vals[field] == None:
			raise Exception("WML key error (PBL IN WML)")

	try:
		addon_type = AddonType.objects.get(type_name=keys_vals['type'])
	except ObjectDoesNotExist:
		return error_response('WML PBL error', ['Addon has a wrong type'])

	try:
		addon = Addon.objects.get(name=keys_vals['title'])
		if len(addon.authors.filter(name=login)) == 0:
			return error_response('Author error', ['This user is not one of authors'])
		addon.uploads += 1
		if addon.file_tbz:
			addon.file_tbz.delete()
		if addon.file_wml:
			addon.file_wml.delete()
	except ObjectDoesNotExist:
		addon = Addon()
		addon.name = keys_vals['title']
		addon.uploads = 1
		addon.downloads = 0

	

	if file_wml != None:
		file_wml.name = addon.name + '.wml'
	else:
		file = open(os.path.join(MEDIA_ROOT, "addons/") + addon.name + ".wml", 'w')
		file.write(file_data)
		file.close()
		file_wml =  "addons/" + addon.name + ".wml"
		

	tmp_dir_name = "%016x" % random.getrandbits(128)
	cs.unpackdir(decoded_wml, tmp_dir_name, verbose = False)
	tarname = os.path.join(MEDIA_ROOT, "addons/") + addon.name + ".tar.bz2"
	Popen(["tar", "cjf", tarname, "-C", tmp_dir_name, '.']).wait()
	shutil.rmtree(tmp_dir_name, True)
	addon.file_tbz = "addons/" + addon.name + ".tar.bz2"

	addon.ver = keys_vals['version']
	addon.img = keys_vals['icon']
	addon.desc = keys_vals['description']
	addon.type = addon_type
	addon.file_wml = file_wml
	addon.lastUpdate = datetime.now()
	addon.save()

	addon.authors.clear()

	authors_str = []
	for author in re.split(r",", keys_vals['author']):
		authors_str.append(author)

	for a in authors_str:
		author = None
		try:
			author = Author.objects.get(name=a)
		except ObjectDoesNotExist:
			author = Author(name=a)
			author.save()
		addon.authors.add(author)
		
	addon.save()

	logger.info(	"User " + login + " from " + request.META['REMOTE_ADDR'] + 
					" has successfully published addon #" + str(addon.id) +
					" ("+addon.name+ ")")
	return render_to_response('addons/publishForm.html', {'publish_success' : True,
								      'loginVal' : login})
        """
        if not os.path.exists(name):
            return None, None

        p = wmlparser.Parser(None)
        p.parse_file(name)
        info = wmldata.DataSub("WML")
        p.parse_top(info)
        uploads = info.get_or_create_sub("info").get_text_val("uploads", "")
        version = info.get_or_create_sub("info").get_text_val("version", "")
        return uploads, version

    campaign_list = None

    if options.list:
        cs = CampaignClient(address)
        campaign_list = data = cs.list_campaigns()
        if data:
            campaigns = data.get_or_create_sub("campaigns")
            if options.wml:
                for campaign in campaigns.get_all("campaign"):
                    campaign.debug(show_contents=True, use_color=options.color)
            else:
                column_sizes = [10, 5, 10, 7, 8, 8, 10, 5, 10, 13]
                columns = [
                    [
                        "type",
                        "name",
                        "title",
                        "author",
                        "version",
        """
        if not os.path.exists(name):
            return None, None

        p = wmlparser.Parser(None)
        p.parse_file(name)
        info = wmldata.DataSub("WML")
        p.parse_top(info)
        uploads = info.get_or_create_sub("info").get_text_val("uploads", "")
        version = info.get_or_create_sub("info").get_text_val("version", "")
        return uploads, version

    campaign_list = None

    if options.list:
        cs = CampaignClient(address)
        campaign_list = data = cs.list_campaigns()
        if data:
            campaigns = data.get_or_create_sub("campaigns")
            if options.wml:
                for campaign in campaigns.get_all("campaign"):
                    campaign.debug(show_contents = True,
                        use_color = options.color)
            else:
                column_sizes = [10, 5, 10, 7, 8, 8, 10, 5, 10, 13]
                columns = [["type", "name", "title", "author",
                    "version", "uploads", "downloads",
                    "size", "timestamp", "translate"]]
                for campaign in campaigns.get_all("campaign"):
                    column = [
                        campaign.get_text_val("type", "?"),