def update(self, request, vendor, name, version, user_name=None): user = user_authentication(request, user_name) gadget = get_object_or_404(Gadget, users=user, vendor=vendor, name=name, version=version) xhtml = gadget.xhtml try: url = xhtml.url if (url.startswith('http')): #Absolute URL xhtml.code = download_http_content(url, user=user) else: #Relative URL if (url.startswith('/deployment/gadgets')): #GWT gadget package xhtml.code = get_xhtml_content(url) else: #Gadget with relative url and it's not a GWT package url = gadget.get_resource_url(url, request) xhtml.code = download_http_content(url, user=user) xhtml.save() except Exception, e: msg = _("XHTML code is not accessible") raise TracedServerError(e, {'vendor': vendor, 'name': name, 'version': version}, request, msg)
def add_user_to_EzSteroids(referer, user): if hasattr(settings, 'AUTHENTICATION_SERVER_URL'): urlBase = settings.AUTHENTICATION_SERVER_URL if (not urlBase.endswith('/')): urlBase += '/' url = urlBase + "api/register" params = {'username': user.username.encode('utf-8')} headers = {'Referer': referer} download_http_content(uri=url, params=params, headers=headers)
def __init__(self, uri): self.uri = uri self.xml = download_http_content(uri) self.handler = None self._capabilities = [] self.uriHandler = UriGadgetHandler () parseString(self.xml, self.uriHandler)
def add_resource_from_template_uri(template_uri, user, fromWGT=False): if fromWGT: localPath = get_wgt_local_path(template_uri) if not path.isfile(localPath): raise Exception(_("'%(file)s' is not a file") % {'file': localPath}) f = open(localPath, 'r') template = f.read() f.close() else: try: template = download_http_content(template_uri, user=user) except HTTPError, e: msg = _("Error downloading resource template '%(url)s': code %(errorCode)s (%(errorMsg)s)") raise TemplateParseException(msg % {'url': template_uri, 'errorCode': e.code, 'errorMsg': e.msg}) except URLError, e: if isinstance(e.reason, str) or isinstance(e.reason, unicode): context = {'errorMsg': e.reason, 'url': template_uri} msg = _("Bad resource template URL '%(url)s': %(errorMsg)s") % context else: context = {'errorMsg': e.reason.strerror, 'url': template_uri} msg = _("Error downloading resource template '%(url)s': %(errorMsg)s") % context raise TemplateParseException(msg)
def parse_gadget_code(main_uri, code_uri, gadget_uri, content_type, from_wgt, cacheable=True, user=None): code = "" url = urlparse.urlparse(code_uri) if url.scheme == 'file': raise TemplateParseException(_('Invalid URL scheme: file')) if from_wgt: local_path = get_wgt_local_path(code_uri) if not os.path.isfile(local_path): raise TemplateParseException(_("'%(file)s' is not a file") % {'file': local_path}) f = open(local_path, 'r') code = f.read() f.close() else: if url.scheme == '': fetch_uri = urlparse.urljoin(main_uri, code_uri) else: fetch_uri = code_uri try: code = http_utils.download_http_content(fetch_uri, user=user) except HTTPError, e: msg = _("Error opening URL: code %(errorCode)s(%(errorMsg)s)") % { 'errorCode': e.code, 'errorMsg': e.msg, } raise TemplateParseException(msg) except URLError, e: msg = _("Error opening URL: %(errorMsg)s") % {'errorMsg': e.reason} raise TemplateParseException(msg)
def is_valid(self, username=None, password=None, request=None): if not username or not request: return (False, None) #ask TCLOUD about the authentication if hasattr(self, 'TCLOUD_AUTH_URL'): org = None cookie = None # Getting user's organization if 'org' in request.REQUEST: org = request.REQUEST['org'] if 'JSESSIONID' in request.COOKIES: cookie = 'JSESSIONID=' + request.COOKIES['JSESSIONID'] if not org or not cookie: return (False, None) url = self.TCLOUD_AUTH_URL % (org, username) params = {} headers = {} headers['Cookie'] = cookie headers['Accept'] = 'application/json' try: result_json = download_http_content(url, params, None, headers) result = simplejson.loads(result_json) return (result['validateSession'], result_json) except Exception: return (False, None)
def __init__(self, uri): self.uri = uri self.xml = download_http_content(uri) self.handler = None self._capabilities = [] self.uriHandler = UriGadgetHandler() parseString(self.xml, self.uriHandler)
def getCategories(user): if hasattr(settings, 'AUTHENTICATION_SERVER_URL'): # Use EzSteroids url = settings.AUTHENTICATION_SERVER_URL + '/api/user/' + user.username + '/categories.json' received_json = download_http_content(url, user=user) return simplejson.loads(received_json)['category_list'] else: # Not use EzSteroids return user.groups.get_query_set()
def parse(self, codeURI, gadgetURI): xhtml = "" # TODO Fixme!! This works for now, but we have to check if a part of a url is empty address = codeURI.split('://') query = address[1].split('/',1) codeURI = address[0] + "://" + query[0] + "/" + urlquote(query[1]) try: xhtml = download_http_content(codeURI) except Exception, e : raise TemplateParseException(_("XHTML code is not accessible"))
def update(self, request, user_name, vendor, name, version): user = user_authentication(request, user_name) gadget = get_object_or_404(Gadget, user=user, vendor=vendor, name=name, version=version) xhtml = gadget.xhtml; try: xhtml.code = download_http_content(xhtml.url) xhtml.save() except Exception, e: msg = _("XHTML code is not accessible") log(msg, request) return HttpResponseServerError(get_xml_error(msg))
def is_valid(self, username=None, password=None): if password == None or password == '': return None #ask PBUMS about the authentication if hasattr(settings, 'AUTHENTICATION_SERVER_URL'): urlBase = settings.AUTHENTICATION_SERVER_URL url = urlBase + "/api/login" params = {'username': username, 'password': password} try: result = download_http_content(url, params) result = simplejson.loads(result) return result['isValid'] except Exception, e: return False
def is_valid(self, username=None, password=None): if username == None or password == '': return None # Ask PBUMS about the authentication if hasattr(settings, 'AUTHENTICATION_SERVER_URL'): urlBase = settings.AUTHENTICATION_SERVER_URL url = urlBase + "/api/login" params = {'username': username.encode('utf-8'), 'password': password.encode('utf-8')} try: result = download_http_content(url, params) result = simplejson.loads(result) return result['isValid'] except Exception: return (False, None)
def render_ezweb(request, user_name=None, template='/', public_workspace='', last_user='', post_load_script='[]'): """ Main view """ if request.META['HTTP_USER_AGENT'].find("iPhone") >= 0 or request.META['HTTP_USER_AGENT'].find("iPod") >= 0: request.session['policies'] = "null" return render_to_response('iphone.html', {}, context_instance=RequestContext(request)) else: #Checking profile! try: user_profile = request.user.get_profile() user_profile.execute_server_script(request) script = user_profile.merge_client_scripts(post_load_script) except Exception: script = post_load_script if hasattr(settings, 'AUTHENTICATION_SERVER_URL'): url = settings.AUTHENTICATION_SERVER_URL if (not url.endswith('/')): url += '/' url = "%sapi/user/%s/data.json" % (url, request.user.username) try: user_data = simplejson.loads(download_http_content(url)) manage_groups(request.user, user_data['groups']) request.session['policies'] = json_encode({"user_policies": user_data['user_policies'], "all_policies": user_data['all_policies']}) except: request.session['policies'] = "null" else: request.session['policies'] = "null" screen_name = get_user_screen_name(request) current_layout = Layout.objects.get(name=settings.LAYOUT) template_file = simplejson.loads(current_layout.templates)[template] context = {'screen_name': screen_name, 'current_tab': 'dragboard', 'active_workspace': public_workspace, 'last_user': last_user, 'post_load_script': script} context.update(get_layout_context(current_layout, request.user)) return render_to_response(template_file, context, context_instance=RequestContext(request))
def is_valid (self,username=None,password=None): if password == None or password == '': return None #ask PBUMS about the authentication if hasattr(settings,'AUTHENTICATION_SERVER_URL'): urlBase=settings.AUTHENTICATION_SERVER_URL; url = urlBase+"/api/login" params = {'username':username, 'password':password} try: result = download_http_content(url,params) result = simplejson.loads(result) return (result['isValid'], result['groups']) except Exception, e: return (False, None)
def update(self, request, user_name, vendor, name, version): user = user_authentication(request, user_name) gadget = get_object_or_404(Gadget, user=user, vendor=vendor, name=name, version=version) xhtml = gadget.xhtml try: xhtml.code = download_http_content(xhtml.url) xhtml.save() except Exception, e: msg = _("XHTML code is not accessible") log(msg, request) return HttpResponseServerError(get_xml_error(msg))
def read(self, request): user = get_user_authentication(request) data_list = {} #boolean for js data_list['isDefault'] = "false" try: workspaces = WorkSpace.objects.filter(users__id=user.id) if workspaces.count() == 0: cloned_workspace = None #it's the first time the user has logged in. #try to assign a default workspace according to user category if hasattr(settings, 'AUTHENTICATION_SERVER_URL'): #ask PBUMS for the category try: url = settings.AUTHENTICATION_SERVER_URL + '/api/user/' + user.username + '/categories.json' received_json = download_http_content(url) categories = simplejson.loads( received_json)['category_list'] if len(categories) > 0: #take the first one which has a default workspace for category in categories: try: default_workspace = Category.objects.get( category_id=category['id'] ).default_workspace #duplicate the workspace for the user cloned_workspace = cloneWorkspace( default_workspace.id) linkWorkspace(user, cloned_workspace.id) setActiveWorkspace(user, cloned_workspace) data_list['isDefault'] = "true" break except Category.DoesNotExist: #the user category doesn't have a default workspace #try with other categories continue except Exception, e: pass if not cloned_workspace: #create an empty workspace createWorkSpace('MyWorkSpace', user) workspaces = WorkSpace.objects.filter(users__id=user.id)
def __init__(self, uri, user, fromWGT, request): self.uri = uri self.user = user self.fromWGT = fromWGT self.request = request if not fromWGT: self.xml = download_http_content(uri, user=user) else: # In this case 'uri' is a filesystem URL localpath = get_wgt_local_path(uri) f = open(localpath, 'r') self.xml = f.read() f.close() self.handler = None self._capabilities = [] self.uriHandler = UriGadgetHandler() parseString(self.xml, self.uriHandler)
def parse(self, codeURI, gadgetURI, content_type): xhtml = "" # TODO Fixme!! This works for now, but we have to check if a part of a url is empty address = codeURI.split('://') query = address[1].split('/',1) codeURI = address[0] + "://" + query[0] + "/" + urlquote(query[1]) try: xhtml = download_http_content(codeURI) except Exception: raise TemplateParseException(_("XHTML code is not accessible")) uri = gadgetURI + "/xhtml" self.xHTML = XHTML (uri=uri, code=xhtml, url=codeURI, content_type=content_type) self.xHTML.save() return
def read(self, request, vendor, name, version, user_name=None): #user = user_authentication(request, user_name) gadget = get_object_or_404(Gadget, vendor=vendor, name=name, version=version) xhtml = get_object_or_404(gadget.xhtml, id=gadget.xhtml.id) content_type = gadget.xhtml.content_type if not content_type: content_type = 'text/html' if not xhtml.cacheable: try: if xhtml.url.startswith('/deployment/gadgets/'): xhtml.code = get_xhtml_content(xhtml.url) else: xhtml.code = download_http_content(gadget.get_resource_url(xhtml.url, request), user=request.user) xhtml.save() except Exception, e: # FIXME: Send the error or use the cached original code? msg = _("XHTML code is not accessible")
def parse_gadget_code(main_uri, code_uri, gadget_uri, content_type, from_wgt, cacheable=True, user=None): code = "" url = urlparse.urlparse(code_uri) if url.scheme == 'file': raise TemplateParseException(_('Invalid URL scheme: file')) if from_wgt: local_path = get_wgt_local_path(code_uri) if not os.path.isfile(local_path): raise TemplateParseException( _("'%(file)s' is not a file") % {'file': local_path}) f = open(local_path, 'r') code = f.read() f.close() else: if url.scheme == '': fetch_uri = urlparse.urljoin(main_uri, code_uri) else: fetch_uri = code_uri try: code = http_utils.download_http_content(fetch_uri, user=user) except HTTPError, e: msg = _("Error opening URL: code %(errorCode)s(%(errorMsg)s)") % { 'errorCode': e.code, 'errorMsg': e.msg, } raise TemplateParseException(msg) except URLError, e: msg = _("Error opening URL: %(errorMsg)s") % {'errorMsg': e.reason} raise TemplateParseException(msg)
def read(self, request): user = get_user_authentication(request) data_list = {} #boolean for js data_list['isDefault']="false" try: workspaces = WorkSpace.objects.filter(users__id=user.id) if workspaces.count()==0: cloned_workspace = None #it's the first time the user has logged in. #try to assign a default workspace according to user category if hasattr(settings, 'AUTHENTICATION_SERVER_URL'): #ask PBUMS for the category try: url = settings.AUTHENTICATION_SERVER_URL + '/api/user/' + user.username + '/categories.json' received_json = download_http_content(url) categories = simplejson.loads(received_json)['category_list'] if len(categories) > 0: #take the first one which has a default workspace for category in categories: try: default_workspace = Category.objects.get(category_id=category['id']).default_workspace #duplicate the workspace for the user cloned_workspace = cloneWorkspace(default_workspace.id) linkWorkspace(user, cloned_workspace.id) setActiveWorkspace(user, cloned_workspace) data_list['isDefault']="true" break except Category.DoesNotExist: #the user category doesn't have a default workspace #try with other categories continue except Exception, e: pass if not cloned_workspace: #create an empty workspace createWorkSpace('MyWorkSpace', user) workspaces = WorkSpace.objects.filter(users__id=user.id)
def read(self, request, vendor, name, version, user_name=None): user = user_authentication(request, user_name) gadget = get_object_or_404(Gadget, vendor=vendor, name=name, version=version, users__id=user.id) xhtml = gadget.xhtml content_type = xhtml.content_type if not content_type: content_type = 'text/html' code = xhtml.code if not xhtml.cacheable or code == '': try: if xhtml.url.startswith('/deployment/gadgets/'): code = get_xhtml_content(xhtml.url) code = includeTagBase(code, xhtml.url, request) else: code = download_http_content(gadget.get_resource_url(xhtml.url, request), user=request.user) code = fix_ezweb_scripts(code, request) except Exception, e: # FIXME: Send the error or use the cached original code? msg = _("XHTML code is not accessible: %(errorMsg)s") % {'errorMsg': e.message} return HttpResponse(get_xml_error(msg), mimetype='application/xml; charset=UTF-8')
def __init__(self, uri, user): self.uri = uri self.xml = download_http_content(uri) self.handler = TemplateHandler(user, uri)
code_files.append(fil) for gadget_file in gadgets_files: template_uri = gadget_file template_uri = "file://%s" % gadget_file gadget_resources = GadgetResource.objects.filter( template_uri=template_uri) for gadget_resource in gadget_resources: gadget_resource.delete() try: catalogue_template_parser = CatalogueTemplateParser( template_uri, user) catalogue_template_parser.parse() except Exception, e: print "The file '%s' is not a valid XML template: %s." % ( gadget_file, e) errors += 1 for code_file in code_files: code_url = "file://%s" % code_file xhtmls = XHTML.objects.filter(url=code_url) for xhtml in xhtmls: try: xhtml.code = download_http_content(xhtml.url) xhtml.save() except Exception, e: print "Unable get contents of %s (%s)." % (code_file, e) print "%s errors found" % errors
def update_gadget_script(request, fromWGT=False, user_action=True): """ Page for adding gadgets to catalogue without loading EzWeb """ if (request.user.is_authenticated() and not request.user.username.startswith('anonymous')): if ('gadget_vendor' in request.REQUEST and 'gadget_name' in request.REQUEST and 'gadget_version' in request.REQUEST): vendor = request.REQUEST['gadget_vendor'] name = request.REQUEST['gadget_name'] version = request.REQUEST['gadget_version'] else: #Send pingback ERROR send_pingback(request, {'result_code': -3, 'result_message': _('Invalid params for gadget update! (gadget_vendor, gadget_name, gadget_version)')}) #template_uri not specified! t = loader.get_template('catalogue_adder.html') c = Context({'msg': _('Invalid params for gadget update! (gadget_vendor, gadget_name, gadget_version)')}) return HttpResponseBadRequest(t.render(c), mimetype="application/xhtml+xml") gadget_info = {'vendor': vendor, 'gadgetName': name, 'version': version} # For ping_back #Cancel by the user if 'pingback_cancel' in request.REQUEST and (request.REQUEST['pingback_cancel'] == 'true'): if 'pingback' in request.REQUEST: #Send pingback CANCEL gadget_info['result_code'] = 1 gadget_info['result_message'] = _('Cancel by the user') send_pingback(request, gadget_info) #Redirect return HttpResponseRedirect('/') try: resource = GadgetResource.objects.get(short_name=name, vendor=vendor, version=version) gadget_info['gadgetId'] = resource.id except Exception: #Send pingback ERROR gadget_info['result_code'] = -3 gadget_info['result_message'] = _('Invalid gadget info! Please, specify a valid one!') send_pingback(request, gadget_info) #Error parsing the template t = loader.get_template('catalogue_adder.html') c = Context({'msg': _('Invalid gadget info! Please, specify a valid one!')}) return HttpResponseBadRequest(t.render(c), mimetype="application/xhtml+xml") gadget = None try: gadget = Gadget.objects.get(name=name, vendor=vendor, version=version) except Exception: pass try: if gadget != None: xhtml = XHTML.objects.get(id=gadget.xhtml.id) content_type = gadget.xhtml.content_type if not content_type: content_type = 'text/html' #if not xhtml.cacheable: if (not xhtml.url.startswith('http') and not xhtml.url.startswith('https')): xhtml.code = get_xhtml_content(xhtml.url) else: xhtml.code = download_http_content(xhtml.url, user=request.user) xhtml.save() except Exception: #Send pingback ERROR gadget_info['result_code'] = -3 gadget_info['result_message'] = _('XHTML code is not accessible!') send_pingback(request, gadget_info) #Error parsing the template t = loader.get_template('catalogue_adder.html') c = Context({'msg': _('XHTML code is not accessible!')}) return HttpResponseBadRequest(t.render(c), mimetype="application/xhtml+xml") #Send pingback OK gadget_info['result_code'] = 0 gadget_info['result_message'] = _('Success') send_pingback(request, gadget_info) # Gadget updated! t = loader.get_template('catalogue_adder.html') c = Context({'msg': _('Gadget updated correctly!')}) return HttpResponse(t.render(c), mimetype="application/xhtml+xml") else: #Not authenticated or anonymous user => redirecting to login! params = {'next': request.META['QUERY_STRING']} if 'pingback' in request.REQUEST: params['pingback'] = request.REQUEST['pingback'] return render_to_response('catalogue_adder_login.html', params, context_instance=RequestContext(request))
def read(self, request): user = get_user_authentication(request) data_list = {} #boolean for js data_list['isDefault']="false" try: #user workspaces workspaces = WorkSpace.objects.filter(users__id=user.id) #workspaces assigned to the user's organizations organizations = user.groups.all() wsGivenByUserOrgs = [] for org in organizations: wsGivenByUserOrgs += list(WorkSpace.objects.filter(targetOrganizations = org)) for ws in wsGivenByUserOrgs: try: workspaces.get(id=ws.id) except WorkSpace.DoesNotExist: #the user doesn't have this workspace (which is assigned to his organizations) #duplicate the workspace for the user linkWorkspace(user, ws.id, ws.get_creator()) #set that the showcase will have to be reloaded #because this workspace is new for the user data_list['isDefault']="true" if data_list['isDefault'] == "false" and workspaces.count() == 0: #There is no workspace for the user cloned_workspace = None #it's the first time the user has logged in. #try to assign a default workspace according to user category if hasattr(settings, 'AUTHENTICATION_SERVER_URL'): #ask PBUMS for the category try: url = settings.AUTHENTICATION_SERVER_URL + '/api/user/' + user.username + '/categories.json' received_json = download_http_content(url) categories = simplejson.loads(received_json)['category_list'] if len(categories) > 0: #take the first one which has a default workspace for category in categories: try: default_workspace = Category.objects.get(category_id=category['id']).default_workspace #duplicate the workspace for the user cloned_workspace = cloneWorkspace(default_workspace.id, user) linkWorkspace(user, cloned_workspace.id, default_workspace.workspace.get_creator()) setActiveWorkspace(user, cloned_workspace) data_list['isDefault']="true" break except Category.DoesNotExist: #the user category doesn't have a default workspace #try with other categories continue except Exception, e: pass if not cloned_workspace: #create an empty workspace createWorkSpace('MyWorkSpace', user) #Now we can fetch all the workspaces of an user workspaces = WorkSpace.objects.filter(users__id=user.id) if UserWorkSpace.objects.filter(user__id=user.id, active=True).count() == 0: #if there is no active workspace #set the first workspace as active setActiveWorkspace(user, workspaces.all()[0])
if fil.endswith('.xml'): gadgets_files.append(fil) else: code_files.append(fil) for gadget_file in gadgets_files: template_uri = gadget_file template_uri = "file://%s" % gadget_file gadget_resources = GadgetResource.objects.filter(template_uri=template_uri) for gadget_resource in gadget_resources: gadget_resource.delete() try: catalogue_template_parser = CatalogueTemplateParser(template_uri, user) catalogue_template_parser.parse() except Exception, e: print "The file '%s' is not a valid XML template: %s." % (gadget_file, e) errors += 1 for code_file in code_files: code_url = "file://%s" % code_file xhtmls = XHTML.objects.filter(url=code_url) for xhtml in xhtmls: try: xhtml.code = download_http_content(xhtml.url) xhtml.save() except Exception, e: print "Unable get contents of %s (%s)." % (code_file, e) print "%s errors found" % errors