def create(self, request, workspace_id, tab_id): user = get_user_authentication(request) if 'igadget' not in request.POST: return HttpResponseBadRequest(get_xml_error(_("iGadget JSON expected")), mimetype='application/xml; charset=UTF-8') # Data checking and parsing try: igadget = simplejson.loads(request.POST['igadget']) except: return HttpResponseBadRequest(get_xml_error(_('iGadget data is not valid JSON'))) initial_variable_values = None if 'variable_values' in request.POST: try: initial_variable_values = simplejson.loads(request.POST['variable_values']) except: return HttpResponseBadRequest(get_xml_error(_('variables_values must be a valid JSON value'))) # iGadget creation try: tab = Tab.objects.get(workspace__users__id=user.id, workspace__pk=workspace_id, pk=tab_id) igadget = SaveIGadget(igadget, user, tab, initial_variable_values) igadget_data = get_igadget_data(igadget, user, tab.workspace) return HttpResponse(json_encode(igadget_data), mimetype='application/json; charset=UTF-8') except Gadget.DoesNotExist, e: msg = _('referred gadget %(gadget_uri)s does not exist.') % {'gadget_uri': igadget['gadget']} raise TracedServerError(e, {'igadget': igadget, 'user': user, 'tab': tab}, request, msg)
def update(self, request, user_name, concept_name): user = user_authentication(request, user_name) received_json = PUT_parameter(request, 'json') if not received_json: return HttpResponseBadRequest(get_xml_error(_("JSON parameter not specified"))) try: received_data = simplejson.loads(received_json) except: return HttpResponseBadRequest(get_xml_error(_("Expecting data in JSON format."))) for received_concept in received_data: concept = None try: concept = Concept.objects.get(concept=concept_name) concept.adaptor = received_concept['adaptor'] concept.save() except Concept.DoesNotExist: return HttpResponseBadRequest(get_xml_error(_("Concept does not exist. You must use POST HTTP method in this case"))) cname = ConceptName (name=received_concept['name'], concept=concept) cname.save() return HttpResponse('ok')
def update(self, request, workspace_id, tab_id): user = get_user_authentication(request) received_json = PUT_parameter(request, 'tab') if not received_json: return HttpResponseBadRequest(get_xml_error(_("tab JSON expected")), mimetype='application/xml; charset=UTF-8') try: t = eval(received_json) tab = Tab.objects.get(workspace__user=user, workspace__pk=workspace_id, pk=tab_id) if t.has_key('visible'): visible = t.get('visible') if (visible == 'true'): #Only one visible tab setVisibleTab(user, workspace_id, tab) else: tab.visible = False if t.has_key('name'): tab.name = t.get('name') tab.save() return HttpResponse('ok') except Exception, e: transaction.rollback() msg = _("tab cannot be updated: ") + unicode(e) log(msg, request) return HttpResponseServerError(get_xml_error(msg), mimetype='application/xml; charset=UTF-8')
def update(self, request, workspace_id): user = get_user_authentication(request) received_json = PUT_parameter(request, 'variables') if not received_json: return HttpResponseBadRequest(get_xml_error(_("variables JSON expected")), mimetype='application/xml; charset=UTF-8') try: variables = eval(received_json) igadgetVariables = variables['igadgetVars'] workSpaceVariables = variables['workspaceVars'] for wsVar in workSpaceVariables: wsVarDAO = WorkSpaceVariable.objects.get(pk=wsVar['id']) wsVarDAO.abstract_variable.value=wsVar['value']; wsVarDAO.abstract_variable.save(); for igVar in igadgetVariables: igVarDAO = Variable.objects.get(pk=igVar['id']) igVarDAO.abstract_variable.value=igVar['value']; igVarDAO.abstract_variable.save(); return HttpResponse(str('OK')) except Exception, e: transaction.rollback() msg = _("cannot update variables: ") + unicode(e) log(msg, request) return HttpResponseServerError(get_xml_error(msg), mimetype='application/xml; charset=UTF-8')
def update(self, request, workspace_id): user = get_user_authentication(request) received_json = PUT_parameter(request, 'workspace') if not received_json: return HttpResponseBadRequest(get_xml_error(_("workspace JSON expected")), mimetype='application/xml; charset=UTF-8') try: ts = simplejson.loads(received_json) workspace = WorkSpace.objects.get(users__id=user.id, pk=workspace_id) if ts.has_key('active'): active = ts.get('active') if (active == 'true'): #Only one active workspace setActiveWorkspace(user, workspace) else: workspace.active = False if ts.has_key('name'): workspace.name = ts.get('name') workspace.save() return HttpResponse('ok') except Exception, e: transaction.rollback() msg = _("workspace cannot be updated: ") + unicode(e) log(msg, request) return HttpResponseServerError(get_xml_error(msg), mimetype='application/xml; charset=UTF-8')
def create(self, request, workspace_id): user = get_user_authentication(request) if not request.POST.has_key('tab'): return HttpResponseBadRequest(get_xml_error(_("tab JSON expected")), mimetype='application/xml; charset=UTF-8') #TODO we can make this with deserializers (simplejson) received_json = request.POST['tab'] try: t = simplejson.loads(received_json) if not t.has_key('name'): raise Exception(_('Malformed tab JSON: expecting tab name.')) tab_name = t.get('name') workspace = WorkSpace.objects.get(users__id=user.id, pk=workspace_id) ids = createTab(tab_name, user, workspace) return HttpResponse(json_encode(ids), mimetype='application/json; charset=UTF-8') except Exception, e: transaction.rollback() msg = _("tab cannot be created: ") + unicode(e) log(msg, request) return HttpResponseServerError(get_xml_error(msg), mimetype='application/xml; charset=UTF-8')
def update(self, request, workspace_id, tab_id): user = get_user_authentication(request) received_json = PUT_parameter(request, 'igadgets') if not received_json: return HttpResponseBadRequest(get_xml_error(_("iGadget JSON expected")), mimetype='application/xml; charset=UTF-8') try: tab = Tab.objects.get(workspace__users__id=user.id, workspace__pk=workspace_id, pk=tab_id) received_data = simplejson.loads(received_json) igadgets = received_data.get('iGadgets') for igadget in igadgets: UpdateIGadget(igadget, user, tab) transaction.commit() return HttpResponse('ok') except Tab.DoesNotExist: msg = _('referred tab %(tab_id)s does not exist.') log(msg, request) return HttpResponseBadRequest(get_xml_error(msg)) except Exception, e: transaction.rollback() msg = _("iGadgets cannot be updated: ") + unicode(e) log(msg, request) return HttpResponseServerError(get_xml_error(msg), mimetype='application/xml; charset=UTF-8')
def create(self, request): user = get_user_authentication(request) if not request.POST.has_key('workspace'): return HttpResponseBadRequest(get_xml_error(_("workspace JSON expected")), mimetype='application/xml; charset=UTF-8') #TODO we can make this with deserializers (simplejson) received_json = request.POST['workspace'] try: ts = simplejson.loads(received_json) if not ts.has_key('name'): raise Exception(_('Malformed workspace JSON: expecting workspace uri.')) workspace_name = ts.get('name') ids = createWorkSpace (workspace_name, user) workspaces = get_list_or_404(WorkSpace, users__id=user.id, pk=ids['workspace']['id']) data = serializers.serialize('python', workspaces, ensure_ascii=False) concept_data = {} concept_data['user'] = user workspace_data = get_global_workspace_data(data[0], workspaces[0], concept_data, user) return HttpResponse(json_encode(workspace_data), mimetype='application/json; charset=UTF-8') except Exception, e: transaction.rollback() msg = _("workspace cannot be created: ") + unicode(e) log(msg, request) return HttpResponseServerError(get_xml_error(msg), mimetype='application/xml; charset=UTF-8')
def update(self, request, workspace_id, tab_id, igadget_id): user = get_user_authentication(request) received_json = PUT_parameter(request, 'variables') # Gets JSON parameter from request if not received_json: return HttpResponseBadRequest(get_xml_error(_("iGadget variables JSON expected")), mimetype='application/xml; charset=UTF-8') try: received_variables = simplejson.loads(received_json) tab = Tab.objects.get(workspace__users__id=user.id, workspace__pk=workspace_id, pk=tab_id) server_variables = Variable.objects.filter(igadget__tab=tab) # Gadget variables collection update for varServer in server_variables: for varJSON in received_variables: if (varServer.vardef.pk == varJSON['pk'] and varServer.igadget.pk == varJSON['iGadget']): varServer.value = varJSON['value'] varServer.save() transaction.commit() except Tab.DoesNotExist: msg = _('referred tab %(tab_id)s does not exist.') log(msg, request) return HttpResponseBadRequest(get_xml_error(msg)) except Exception, e: transaction.rollback() log(e, request) return HttpResponseServerError(get_xml_error(unicode(e)), mimetype='application/xml; charset=UTF-8')
def create(self, request, user_name): user = user_authentication(request, user_name) if request.POST.has_key('json'): received_json = request.POST['json'] else: return HttpResponseBadRequest(get_xml_error(_("JSON parameter not specified"))) try: received_data = simplejson.loads(received_json) except: return HttpResponseBadRequest(get_xml_error(_("Expecting data in JSON format."))) for received_concept in received_data['concepts']: concept = None try: concept = Concept.objects.get(concept=received_concept['concept']) if not concept.adaptor == received_concept['adaptor']: return HttpResponseBadRequest(get_xml_error(_(u'Attempted update. You must use PUT HTTP method in this case'))) except Concept.DoesNotExist: concept = Concept (concept=received_concept['concept'], adaptor=received_concept['adaptor']) concept.save() try: #Checks if concept name exits in database ConceptName.objects.get (name=received_concept['name'], concept=concept) except ConceptName.DoesNotExist: cname = ConceptName (name=received_concept['name'], concept=concept) cname.save() return HttpResponse('ok')
def create(self, request): try: if request.get_host() != urlparse.urlparse(request.META["HTTP_REFERER"])[1]: return HttpResponseServerError(get_xml_error(_(u"Invalid request Referer")), mimetype='application/xml; charset=UTF-8') except: return HttpResponseServerError(get_xml_error(_(u"Invalid request Referer")), mimetype='application/xml; charset=UTF-8') # URI to be called if request.POST.has_key('url'): url = request.POST['url'] else: return HttpResponseNotFound(get_xml_error(_(u"Url not specified")), mimetype='application/xml; charset=UTF-8') # HTTP method, by default is GET if request.POST.has_key('method'): method = request.POST['method'].upper() else: method = "GET" # Params if method != 'GET' and request.POST.has_key('params'): # if Content-Type is xml or json then skipping encode function. if re.search("application/(json|xml|[a-zA-Z-]+\+xml)|text/xml", request.META["CONTENT_TYPE"]) != None: params = request.POST['params'].encode('utf-8') else: try: params = urlencode(simplejson.loads(request.POST['params'])) except Exception, e: params = encode_query(request.POST['params'])
def create(self, request): if not request.user.is_authenticated(): return HttpResponseForbidden(_('Your must be logged in to access this service')) try: if request.get_host() != urlparse.urlparse(request.META["HTTP_REFERER"])[1]: return HttpResponseServerError(get_xml_error(_(u"Invalid request Referer")), mimetype='application/xml; charset=UTF-8') except: return HttpResponseServerError(get_xml_error(_(u"Invalid request Referer")), mimetype='application/xml; charset=UTF-8') # URI to be called if 'url' in request.POST: url = request.POST['url'] else: return HttpResponseNotFound(get_xml_error(_(u"Url not specified")), mimetype='application/xml; charset=UTF-8') # HTTP method, by default is GET method = request.POST.get('method', 'GET').upper() # Params if method != 'GET' and 'params' in request.POST: # if Content-Type is xml or json then skipping encode function. if re.search("application/(json|xml|[a-zA-Z-]+\+xml)|text/xml", request.META["CONTENT_TYPE"]) != None: params = request.POST['params'].encode('utf-8') else: try: params = urlencode(simplejson.loads(request.POST['params'])) except Exception: params = encode_query(request.POST['params']) else: params = None return self.do_request(request, url, method, params)
def create(self, request, user_name=None): """ Purchases one gadget using a GadgetPricing ID Checks if there is any active transaction and if there is enough balance in the user wallet. Creates a transaction and substract the amount from the wallet ballance """ user = get_user_authentication(request) # gets user wallet information user_wallet = Wallet.objects.get(auth_user=user) # gets gadget pricing information pricing_id = request.POST.__getitem__('pricing_id') pricing = GadgetPricing.objects.get(id=pricing_id) # First check: Is gadget purchased? active_transaction = self._check_purchased_gadget(user_wallet, pricing.gadget.short_name, pricing.gadget.vendor, pricing.gadget.version) if active_transaction == True: return HttpResponseServerError(get_xml_error(_("Gadget is currently purchased")), mimetype='application/xml; charset=UTF-8') # Second check: Is there enough balance if pricing.price > user_wallet.current_balance: return HttpResponseServerError(get_xml_error(_("There is not enough balance")), mimetype='application/xml; charset=UTF-8') # creates the transaction transaction = Transaction() transaction.wallet = user_wallet transaction.creation_date = datetime.now() transaction.transaction_type = 'P' transaction.concept = _('Gadget purchasing') transaction.amount = pricing.price transaction.status = 'C' transaction.gadget_pricing = pricing if pricing.periodicity == "P": transaction.finish_date = transaction.creation_date else: if pricing.periodicity == "D": duration = timedelta(days=pricing.duration) if pricing.periodicity == "W": duration = timedelta(weeks=pricing.duration) if pricing.periodicity == "M": duration = timedelta(days=pricing.duration*30) if pricing.periodicity == "Y": duration = timedelta(days=pricing.duration*365) transaction.finish_date = transaction.creation_date + duration #transaction.payment_item = 0 transaction.save() # Updates the user wallet user_wallet.current_balance -= pricing.price user_wallet.outstanding_balance -= pricing.price user_wallet.save() # returns the affected information return HttpResponse(json_encode({ "wallet": user_wallet, "pricing": pricing, "transaction": transaction}), mimetype='application/json; charset=UTF-8')
def update(self, request, user_name, igadget_id=None, screen_id=None): user = user_authentication(user_name) # Gets JSON parameter from request if not request.PUT.has_key('variables'): return HttpResponseBadRequest(get_xml_error(_("iGadget variables JSON expected")), mimetype='application/xml; charset=UTF-8') variables_JSON = request.PUT['variables'] try: received_variables = eval(variables_JSON) except Exception, e: return HttpResponseBadRequest(get_xml_error(unicode(e)), mimetype='application/xml; charset=UTF-8')
def create(self, request, workspace_id): if 'data' not in request.REQUEST: return HttpResponseBadRequest(get_xml_error(_("mashup data expected")), mimetype='application/xml; charset=UTF-8') received_json = request.REQUEST['data'] try: mashup = simplejson.loads(received_json) missing_fields = check_json_fields(mashup, ['name', 'vendor', 'version', 'email']) if len(missing_fields) > 0: raise Exception(_('Malformed mashup JSON. The following field(s) are missing: %(fields)s.') % {'fields': missing_fields}) except Exception, e: msg = _("mashup cannot be published: ") + unicode(e) return HttpResponseBadRequest(get_xml_error(msg), mimetype='application/xml; charset=UTF-8')
def read(self, request, user_name=None): user = get_user_authentication(request) user_wallet = None try: user_wallet = Wallet.objects.get(auth_user=user) except Exception, e: return HttpResponseServerError(get_xml_error(unicode(e)), mimetype='application/xml; charset=UTF-8')
def update(self, request, workspace_id): user = get_user_authentication(request) content_type = request.META.get('CONTENT_TYPE', '') if content_type == None: content_type = '' if content_type.startswith('application/json'): received_json = request.raw_post_data else: received_json = PUT_parameter(request, 'variables') if not received_json: return HttpResponseBadRequest(get_xml_error(_("variables JSON expected")), mimetype='application/xml; charset=UTF-8') try: variables = simplejson.loads(received_json) igadgetVariables = variables['igadgetVars'] variables_to_notify = [] for igVar in igadgetVariables: variables_to_notify += set_variable_value(igVar['id'], user, igVar['value']) data = {'igadgetVars': variables_to_notify} return HttpResponse(json_encode(data), mimetype='application/json; charset=UTF-8') except Exception, e: transaction.rollback() msg = _("cannot update variables: ") + unicode(e) raise TracedServerError(e, received_json, request, msg)
def create(self, request, workspace_id): user = get_user_authentication(request) if 'tab' not in request.POST: return HttpResponseBadRequest(get_xml_error(_("tab JSON expected")), mimetype='application/xml; charset=UTF-8') #TODO we can make this with deserializers (simplejson) received_json = request.POST['tab'] try: t = simplejson.loads(received_json) if 'name' not in t: raise Exception(_('Malformed tab JSON: expecting tab name.')) tab_name = t['name'] workspace = WorkSpace.objects.get(users__id=user.id, pk=workspace_id) tab = createTab(tab_name, user, workspace) # Returning created Ids ids = {'id': tab.id, 'name': tab.name} return HttpResponse(json_encode(ids), mimetype='application/json; charset=UTF-8') except Exception, e: transaction.rollback() msg = _("tab cannot be created: ") + unicode(e) raise TracedServerError(e, t, request, msg)
def create(self, request, user_name=None): user = get_user_authentication(request) if request.POST.has_key('url'): templateURL = request.POST['url'] else: return HttpResponseServerError('<error>Url not specified</error>', mimetype='application/xml; charset=UTF-8') ########### Template Parser templateParser = None try: # Gadget is created only once templateParser = TemplateParser(templateURL) gadget_uri = templateParser.getGadgetUri() try: gadget = Gadget.objects.get(uri=gadget_uri) except Gadget.DoesNotExist: # Parser creates the gadget. It's made only if the gadget does not exist templateParser.parse() gadget = templateParser.getGadget() # A new user has added the gadget in his showcase gadget.users.add(user) transaction.commit() except TemplateParseException, e: log(e, request) transaction.rollback() return HttpResponseServerError(get_xml_error(unicode(e)), mimetype='application/xml; charset=UTF-8')
def read(self, request, vendor=None, name=None, version=None): """ Gets a price list for a gadget specified by vendor, gadget name and gadget version """ gadget_pricing = None try: # Gets the standard pricing method gadget_pricing = GadgetPricing.objects.filter(gadget__short_name=name, gadget__vendor=vendor, gadget__version=version) if hasattr(settings,'AUTHENTICATION_SERVER_URL'): user = get_user_authentication(request) # Gets the current user categories via ezsteroids API user_categories = _user_categories_tuple(user) gadget_special_pricings = GadgetSpecialPricing.objects.filter(pricing__gadget__short_name=name, pricing__gadget__vendor=vendor, pricing__gadget__version=version) # Refines the special pricing for gadget_special_pricing in gadget_special_pricings: for user_category in user_categories: if user_category[0] == gadget_special_pricing.user_category : for index, gadget_pricing_item in enumerate(gadget_pricing) : if(gadget_pricing_item.id == gadget_special_pricing.pricing.id) and \ (gadget_pricing_item.price > gadget_special_pricing.price) : gadget_pricing[index].price = gadget_special_pricing.price except Exception: return HttpResponseServerError(get_xml_error(_("Error retrieving gadgets pricing")), mimetype='application/xml; charset=UTF-8') return HttpResponse(json_encode(gadget_pricing), mimetype='application/json; charset=UTF-8')
def delete(self, request, workspace_id, tab_id): user = get_user_authentication(request) #set new order tabs = Tab.objects.filter(workspace__pk=workspace_id).order_by('position') # Get tab, if it does not exist, an http 404 error is returned tab = get_object_or_404(Tab, workspace__pk=workspace_id, pk=tab_id) #decrease the position of the following tabs for t in range(tab.position, tabs.count()): tabs[t].position = tabs[t].position - 1 tabs = tabs.exclude(pk=tab_id) if tabs.count()==0: msg = _("tab cannot be deleted") log(msg, request) return HttpResponseServerError(get_xml_error(msg), mimetype='application/xml; charset=UTF-8') #Delete WorkSpace variables too! deleteTab(tab, user) #set a new visible tab (first tab by default) activeTab=tabs[0] setVisibleTab(user, workspace_id, activeTab) return HttpResponse('ok')
def update(self, request, user_name): user = get_user_authentication(request) received_json = PUT_parameter(request, 'preferences') if not received_json: return HttpResponseBadRequest(get_xml_error(_("Platform Preferences JSON expected")), mimetype='application/xml; charset=UTF-8') try: preferences_json = simplejson.loads(received_json) update_preferences(user, preferences_json) return HttpResponse('ok') except Exception, e: transaction.rollback() msg = _("Platform Preferences cannot be updated: ") + unicode(e) log(msg, request) return HttpResponseServerError(get_xml_error(msg), mimetype='application/xml; charset=UTF-8')
def update(self, request, workspace_id, tab_id): user = get_user_authentication(request) received_json = PUT_parameter(request, 'tab') if not received_json: return HttpResponseBadRequest(get_xml_error(_("tab JSON expected")), mimetype='application/xml; charset=UTF-8') try: t = simplejson.loads(received_json) tab = Tab.objects.get(workspace__users__id=user.id, workspace__pk=workspace_id, pk=tab_id) if 'visible' in t: visible = t['visible'] if (visible == 'true'): #Only one visible tab setVisibleTab(user, workspace_id, tab) else: tab.visible = False if 'name' in t: tab.name = t['name'] tab.save() return HttpResponse('ok') except Exception, e: transaction.rollback() msg = _("tab cannot be updated: ") + unicode(e) raise TracedServerError(e, received_json, request, msg)
def create(self, request): user = get_user_authentication(request) if 'workspace' not in request.POST: return HttpResponseBadRequest(get_xml_error(_("workspace JSON expected")), mimetype='application/xml; charset=UTF-8') #TODO we can make this with deserializers (simplejson) received_json = request.POST['workspace'] try: ts = simplejson.loads(received_json) if 'name' not in ts: raise Exception(_('Malformed workspace JSON: expecting workspace uri.')) workspace_name = ts['name'] workspace = createWorkSpace(workspace_name, user) workspace_data = get_global_workspace_data(workspace, user) return HttpResponse(json_encode(workspace_data), mimetype='application/json; charset=UTF-8') except Exception, e: transaction.rollback() msg = _("workspace cannot be created: ") + unicode(e) raise TracedServerError(e, ts, request, msg)
def update(self, request, workspace_id, last_user=''): user = get_user_authentication(request) received_json = PUT_parameter(request, 'workspace') if not received_json: return HttpResponseBadRequest(get_xml_error(_("workspace JSON expected")), mimetype='application/xml; charset=UTF-8') try: ts = simplejson.loads(received_json) workspace = WorkSpace.objects.get(users__id=user.id, pk=workspace_id) if 'active' in ts: active = ts['active'] if (active == 'true'): #Only one active workspace setActiveWorkspace(user, workspace) else: currentUserWorkspace = UserWorkSpace.objects.get(workspace=workspace, user=user) currentUserWorkspace.active = True currentUserWorkspace.save() if 'name' in ts: workspace.name = ts['name'] workspace.save() return HttpResponse('ok') except Exception, e: transaction.rollback() msg = _("workspace cannot be updated: ") + unicode(e) raise TracedServerError(e, ts, request, msg)
def update(self, request, user_name, igadget_id, screen_id=None): user = user_authentication(user_name) #TODO by default. Remove in final release if not screen_id: screen_id = 1 if not request.PUT.has_key('igadget'): return HttpResponseBadRequest(get_xml_error(_("iGadget JSON expected")), mimetype='application/xml; charset=UTF-8') #TODO we can make this with deserializers (simplejson) received_json = request.PUT['igadget'] try: igadget = eval(received_json) except Exception, e: return HttpResponseBadRequest(get_xml_error(unicode(e)), mimetype='application/xml; charset=UTF-8')
def delete(self,request,user_name,vendor,name,version, tag): try: user = user_authentication(request, user_name) except Http403, e: msg = _("This tag cannot be deleted: ") + unicode(e) log (msg, request) return HttpResponseForbidden(get_xml_error(msg), mimetype='application/xml; charset=UTF-8')
def create(self, request, account_id=None, wallet_id=None): # Gets the attached wallet try: user_wallet = Wallet.objects.get(id=wallet_id) account = Account.objects.get(id=account_id) except Exception, e: log(e, request) return HttpResponseServerError(get_xml_error(_("Error getting objects")), mimetype='application/xml; charset=UTF-8')
def create(self, request, user_name): content_type = request.META.get('CONTENT_TYPE', '') if content_type == None: content_type = '' if content_type.startswith('application/json'): received_json = request.raw_post_data else: received_json = request.POST.get('resources', None) if not received_json: return HttpResponseBadRequest(get_xml_error(_("resources JSON expected")), mimetype='application/xml; charset=UTF-8') try: resources = simplejson.loads(received_json) except simplejson.JSONDecodeError, e: return HttpResponse(get_xml_error(_("malformed json data: %s") % unicode(e)), status=422, mimetype='application/xml; charset=UTF-8')
def public_ws_viewer(request, public_ws_id): """ EzWeb viewer """ try: workspace = WorkSpace.objects.get(id=public_ws_id) except WorkSpace.DoesNotExist: return HttpResponseServerError(get_xml_error(_('the workspace does not exist')), mimetype='application/xml; charset=UTF-8') last_user = '' if (request.user and request.user.username != 'public' and request.user.username != ''): last_user = request.user public_user=login_public_user(request) request.user=public_user if (len(workspace.users.filter(username=public_user.username)) == 1): return render_ezweb(request, template="index_viewer.html", public_workspace=public_ws_id, last_user=last_user) return HttpResponseServerError(get_xml_error(_('the workspace is not shared')), mimetype='application/xml; charset=UTF-8')
def read(self, request): user = get_user_authentication(request) data_list = {} try: workspaces = WorkSpace.objects.filter(users__id=user.id) if workspaces.count() == 0: createWorkSpace('MyWorkSpace', user) workspaces = WorkSpace.objects.filter(users__id=user.id) except Exception, e: log(e, request) return HttpResponseBadRequest( get_xml_error(unicode(e)), mimetype='application/xml; charset=UTF-8')
def update(self, request, workspace_id, tab_id): user = get_user_authentication(request) received_json = PUT_parameter(request, 'tab') if not received_json: return HttpResponseBadRequest( get_xml_error(_("tab JSON expected")), mimetype='application/xml; charset=UTF-8') try: t = eval(received_json) tab = Tab.objects.get(workspace__user=user, workspace__pk=workspace_id, pk=tab_id) if t.has_key('visible'): visible = t.get('visible') if (visible == 'true'): #Only one visible tab setVisibleTab(user, workspace_id, tab) else: tab.visible = False if t.has_key('name'): tab.name = t.get('name') tab.save() return HttpResponse('ok') except Exception, e: transaction.rollback() msg = _("tab cannot be updated: ") + unicode(e) log(msg, request) return HttpResponseServerError( get_xml_error(msg), mimetype='application/xml; charset=UTF-8')
class IGadgetEntry(Resource): def read(self, request, user_name, igadget_id, screen_id=None): user = user_authentication(user_name) #TODO by default. Remove in final release if not screen_id: screen_id = 1 data_list = {} #Gets current user screen screen = Screen.objects.get(user=user, code=screen_id) igadget = get_list_or_404(IGadget, screen=screen, code=igadget_id) data = serializers.serialize('python', igadget, ensure_ascii=False) igadget_data = get_igadget_data(data[0]) return HttpResponse(json_encode(igadget_data), mimetype='application/json; charset=UTF-8') @transaction.commit_on_success def create(self, request, user_name, igadget_id, screen_id=None): user = user_authentication(user_name) #TODO by default. Remove in final release if not screen_id: screen_id = 1 if not request.has_key('igadget'): return HttpResponseBadRequest( get_xml_error(_("iGadget JSON expected")), mimetype='application/xml; charset=UTF-8') #TODO we can make this with deserializers (simplejson) received_json = request.POST['igadget'] try: igadget = eval(received_json) except Exception, e: return HttpResponseBadRequest( get_xml_error(unicode(e)), mimetype='application/xml; charset=UTF-8') try: SaveIGadget(igadget, user, screen_id, igadget_id) return HttpResponse('ok') except Exception, e: return HttpResponseServerError( get_xml_error(_("iGadgets cannot be saved: ") + unicode(e)), mimetype='application/xml; charset=UTF-8')
def get_vote_response(gadget, user, format): if format == 'json' or format == 'default': vote = {} vote_data = get_vote_data(gadget, user) vote['voteData'] = vote_data return HttpResponse(json_encode(vote), mimetype='application/json; charset=UTF-8') elif format == 'xml': response = '<?xml version="1.0" encoding="UTF-8" ?>\n' response += get_vote_by_resource(gadget, user) return HttpResponse(response, mimetype='text/xml; charset=UTF-8') else: return HttpResponseServerError( get_xml_error( _("Invalid format. Format must be either xml or json")), mimetype='application/xml; charset=UTF-8')
def update(self, request, user_name): user = get_user_authentication(request) received_json = PUT_parameter(request, 'preferences') if not received_json: return HttpResponseBadRequest(get_xml_error(_("Platform Preferences JSON expected")), mimetype='application/xml; charset=UTF-8') try: preferences_json = simplejson.loads(received_json) update_preferences(user, preferences_json) return HttpResponse('ok') except Exception, e: transaction.rollback() msg = _("Platform Preferences cannot be updated: ") + unicode(e) raise TracedServerError(e, {}, request, msg)
def create(self, request, user_name, vendor, name, version): try: format = request.POST.__getitem__('format') except: format = 'default' user = user_authentication(request, user_name) # Get the xml containing the tags from the request tags_xml = request.POST.__getitem__('tags_xml') tags_xml = tags_xml.encode("utf-8") # Parse the xml containing the tags parser = make_parser() handler = TagsXMLHandler() # Tell the parser to use our handler parser.setContentHandler(handler) # Parse the input try: from StringIO import StringIO except ImportError: from cStringIO import StringIO inpsrc = InputSource() inpsrc.setByteStream(StringIO(tags_xml)) parser.parse(inpsrc) # Get the gadget's id for those vendor, name and version gadget = get_object_or_404(GadgetResource, short_name=name, vendor=vendor, version=version) # Insert the tags for these resource and user in the database for e in handler._tags: try: UserTag.objects.get_or_create(tag=e, idUser=user, idResource=gadget) except Exception, ex: log(ex, request) return HttpResponseServerError( get_xml_error(unicode(ex)), mimetype='application/xml; charset=UTF-8')
def get_tag_response(gadget, user, format): if format == 'json' or format == 'default': tag = {} tag_data_list = get_tag_data(gadget, user.id) tag['tagList'] = tag_data_list return HttpResponse(json_encode(tag), mimetype='application/json; charset=UTF-8') elif format == 'xml': response = '<?xml version="1.0" encoding="UTF-8" ?>\n' response += get_tags_by_resource(gadget, user) return HttpResponse(response, mimetype='text/xml; charset=UTF-8') else: return HttpResponseServerError( get_xml_error( _("Invalid format. Format must be either xml or json")), mimetype='application/xml; charset=UTF-8')
def __call__(self, request, *args, **kwargs): try: return self.dispatch(request, self, *args, **kwargs) except HttpMethodNotAllowed: response = HttpResponseNotAllowed(self.permitted_methods) response.mimetype = self.mimetype return response except: exc_info = sys.exc_info() msg_array = traceback.format_exception(exc_info[0], exc_info[1], exc_info[2]) msg = "" for line in msg_array: msg += line log(msg, request) msg = "[" + unicode(exc_info[0]) + "] " + unicode(exc_info[1]) return HttpResponseServerError(get_xml_error(msg), mimetype='application/xml; charset=UTF-8')
def get_resource_response(gadgetlist, format, items, user): if format == 'json' or format=='default': gadgetresource = {} resource_data = serializers.serialize('python', gadgetlist, ensure_ascii=False) resource_data_list = [get_gadgetresource_data(d, user) for d in resource_data] gadgetresource['resourceList'] = resource_data_list response = HttpResponse(json_encode(gadgetresource), mimetype='application/json; charset=UTF-8') response.__setitem__('items', items) return response elif format == 'xml': response = get_xml_description(gadgetlist, user) response = HttpResponse(response,mimetype='text/xml; charset=UTF-8') response.__setitem__('items', items) return response else: return HttpResponseServerError(get_xml_error(_("Invalid format. Format must be either xml or json")), mimetype='application/xml; charset=UTF-8')
def read(self, request, vendor=None, name=None, version=None): """ Gets a price list for a gadget specified by vendor, gadget name and gadget version """ gadget_pricing = None try: gadget_pricing = GadgetPricing.objects.filter( gadget__short_name=name, gadget__vendor=vendor, gadget__version=version) except Exception: return HttpResponseServerError( get_xml_error(_("Error retrieving gadgets pricing")), mimetype='application/xml; charset=UTF-8') return HttpResponse(json_encode(gadget_pricing), mimetype='application/json; charset=UTF-8')
def create(self, request, user_name): template_uri = request.__getitem__('template_uri') templateParser = None try: templateParser = TemplateParser(template_uri, user_name) templateParser.parse() transaction.commit() except IntegrityError, e: # Gadget already exists. Rollback transaction transaction.rollback() log(e, 'POST', 'user/id/resources', user_name) return HttpResponseServerError( get_xml_error(unicode(sys.exc_info()[1])), mimetype='application/xml; charset=UTF-8')
class WorkSpaceCollection(Resource): @transaction.commit_on_success 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) except Exception, e: log(e, request) return HttpResponseBadRequest(get_xml_error(unicode(e)), mimetype='application/xml; charset=UTF-8')
def read(self, request, workspace_id): workspace = get_object_or_404(WorkSpace, id=workspace_id) user = get_user_authentication(request) #Checking if user is already linked to workspace if (len(workspace.users.filter(id=user.id)) > 0): msg = _("already linked workspace") log(msg, request) return HttpResponseServerError( get_xml_error(msg), mimetype='application/xml; charset=UTF-8') packageLinker = PackageLinker() packageLinker.link_workspace(workspace, user) return HttpResponse("{'result': 'ok'}", mimetype='application/json; charset=UTF-8')
def delete(self, request, workspace_id): user = get_user_authentication(request) workspaces = WorkSpace.objects.filter(users__id=user.id).exclude(pk=workspace_id) if workspaces.count()==0: msg = _("workspace cannot be deleted") log(msg, request) return HttpResponseServerError(get_xml_error(msg), mimetype='application/xml; charset=UTF-8') # Gets Igadget, if it does not exist, a http 404 error is returned workspace = get_object_or_404(WorkSpace, users__id=user.id, pk=workspace_id) workspace.delete() #set a new active workspace (first workspace by default) activeWorkspace=workspaces[0] setActiveWorkspace(user, activeWorkspace) return HttpResponse('ok')
def create(self, request, workspace_id): if not request.REQUEST.has_key('data'): return HttpResponseBadRequest(get_xml_error(_("mashup data expected")), mimetype='application/xml; charset=UTF-8') received_json = request.REQUEST['data'] try: mashup = simplejson.loads(received_json) if not mashup.has_key('name'): raise Exception(_('Malformed mashup JSON: expecting mashup name.')) if not mashup.has_key('vendor'): raise Exception(_('Malformed mashup JSON: expecting mashup vendor.')) if not mashup.has_key('version'): raise Exception(_('Malformed mashup JSON: expecting mashup version.')) except Exception, e: transaction.rollback() msg = _("mashup cannot be published: ") + unicode(e) raise TracedServerError(e, mashup, request, msg)
def update(self, request, vendor, name, version, user_name=None): user = get_user_authentication(request) gadget = get_object_or_404(Gadget, users=user, vendor=vendor, name=name, version=version) xhtml = gadget.xhtml try: xhtml.code = download_http_content(xhtml.url) xhtml.save() except Exception: msg = _("XHTML code is not accessible") log(msg, request) return HttpResponseServerError(get_xml_error(msg)) return HttpResponse('ok')
def create(self, request): user = get_user_authentication(request) if not request.POST.has_key('workspace'): return HttpResponseBadRequest( get_xml_error(_("workspace JSON expected")), mimetype='application/xml; charset=UTF-8') #TODO we can make this with deserializers (simplejson) received_json = request.POST['workspace'] try: ts = simplejson.loads(received_json) if not ts.has_key('name'): raise Exception( _('Malformed workspace JSON: expecting workspace uri.')) workspace_name = ts.get('name') ids = createWorkSpace(workspace_name, user) workspaces = get_list_or_404(WorkSpace, users__id=user.id, pk=ids['workspace']['id']) data = serializers.serialize('python', workspaces, ensure_ascii=False) concept_data = {} concept_data['user'] = user workspace_data = get_global_workspace_data(data[0], workspaces[0], concept_data, user) return HttpResponse(json_encode(workspace_data), mimetype='application/json; charset=UTF-8') except Exception, e: transaction.rollback() msg = _("workspace cannot be created: ") + unicode(e) raise TracedServerError(e, ts, request, msg)
def update(self, request, user_name, workspace_id, tab_id): user = get_user_authentication(request) received_json = PUT_parameter(request, 'preferences') if not received_json: return HttpResponseBadRequest(get_xml_error(_("Platform Preferences JSON expected")), mimetype='application/xml; charset=UTF-8') try: preferences_json = simplejson.loads(received_json) # Check Tab existance and owned by this user tab = get_object_or_404(Tab, workspace__users__id=user.id, workspace__pk=workspace_id, pk=tab_id) update_tab_preferences(tab, preferences_json) return HttpResponse('ok') except Exception, e: transaction.rollback() msg = _("Tab Preferences could not be updated: ") + unicode(e) raise TracedServerError(e, {}, request, msg)
def delete(self, request, workspace_id, tab_id): user = get_user_authentication(request) tabs = Tab.objects.filter(workspace__pk=workspace_id).exclude(pk=tab_id) if tabs.count()==0: msg = _("tab cannot be deleted") log(msg, request) return HttpResponseServerError(get_xml_error(msg), mimetype='application/xml; charset=UTF-8') # Gets Igadget, if it does not exist, a http 404 error is returned tab = get_object_or_404(Tab, workspace__pk=workspace_id, pk=tab_id) #Delete WorkSpace variables too! deleteTab(tab, user) #set a new visible tab (first tab by default) activeTab=tabs[0] setVisibleTab(user, workspace_id, activeTab) return HttpResponse('ok')
def update(self, request, workspace_id): user = get_user_authentication(request) received_json = PUT_parameter(request, 'variables') if not received_json: return HttpResponseBadRequest( get_xml_error(_("variables JSON expected")), mimetype='application/xml; charset=UTF-8') try: variables = simplejson.loads(received_json) igadgetVariables = variables['igadgetVars'] workSpaceVariables = variables['workspaceVars'] for wsVar in workSpaceVariables: wsVarDAO = WorkSpaceVariable.objects.get(pk=wsVar['id']) variable_value = VariableValue.objects.get( user=user, abstract_variable=wsVarDAO.abstract_variable) variable_value.value = unicode(wsVar['value']) variable_value.save() for igVar in igadgetVariables: igVarDAO = Variable.objects.get(pk=igVar['id']) variable_value = VariableValue.objects.get( user=user, abstract_variable=igVarDAO.abstract_variable) variable_value.value = unicode(igVar['value']) variable_value.save() return HttpResponse(str('OK')) except Exception, e: transaction.rollback() msg = _("cannot update variables: ") + unicode(e) raise TracedServerError(e, variables, request, msg)
def create(self, request, user_name, vendor, name, version): format = request.GET.get('format', 'default') user = user_authentication(request, user_name) # Get the vote from the request vote = request.POST.get('vote') # Get the gadget's id for those vendor, name and version gadget = get_object_or_404(GadgetResource, short_name=name, vendor=vendor, version=version) # Insert the vote for these resource and user in the database try: UserVote.objects.create(vote=vote, idUser=user, idResource=gadget) except Exception, ex: log(ex, request) return HttpResponseServerError( get_xml_error(unicode(ex)), mimetype='application/xml; charset=UTF-8')
def update(self, request, user_name, igadget_id, var_name, screen_id=None): user = user_authentication(user_name) # Gets value parameter from request if not request.PUT.has_key('value'): return HttpResponseBadRequest( get_xml_error(_("iGadget JSON expected")), mimetype='application/xml; charset=UTF-8') new_value = request.PUT['value'] #TODO by default. Remove in final release if not screen_id: screen_id = 1 screen = Screen.objects.get(user=user, code=screen_id) variable = get_object_or_404(Variable, igadget__screen=screen, igadget__code=igadget_id, vardef__name=var_name) variable.value = new_value variable.save() return HttpResponse('ok')
def update(self, request, workspace_id, tab_id, igadget_id): user = get_user_authentication(request) received_json = PUT_parameter(request, 'variables') # Gets JSON parameter from request if not received_json: return HttpResponseBadRequest( get_xml_error(_("iGadget variables JSON expected")), mimetype='application/xml; charset=UTF-8') try: received_variables = simplejson.loads(received_json) tab = Tab.objects.get(workspace__users__id=user.id, workspace__pk=workspace_id, pk=tab_id) server_variables = Variable.objects.filter(igadget__tab=tab) # Gadget variables collection update for varServer in server_variables: for varJSON in received_variables: if (varServer.vardef.pk == varJSON['pk'] and varServer.igadget.pk == varJSON['iGadget']): varServer.value = varJSON['value'] varServer.save() transaction.commit() except Tab.DoesNotExist, e: msg = _('referred tab %(tab_id)s does not exist.') % { 'tab_id': tab_id } raise TracedServerError(e, { 'workspace': workspace_id, 'tab': tab_id, 'igadget': igadget_id }, request, msg)
def update(self, request, workspace_id, last_user=''): user = get_user_authentication(request) received_json = PUT_parameter(request, 'workspace') if not received_json: return HttpResponseBadRequest( get_xml_error(_("workspace JSON expected")), mimetype='application/xml; charset=UTF-8') try: ts = simplejson.loads(received_json) workspace = WorkSpace.objects.get(users__id=user.id, pk=workspace_id) if 'active' in ts: active = ts['active'] if (active == 'true'): #Only one active workspace setActiveWorkspace(user, workspace) else: currentUserWorkspace = UserWorkSpace.objects.get( workspace=workspace, user=user) currentUserWorkspace.active = True currentUserWorkspace.save() if 'name' in ts: workspace.name = ts['name'] workspace.save() return HttpResponse('ok') except Exception, e: transaction.rollback() msg = _("workspace cannot be updated: ") + unicode(e) raise TracedServerError(e, ts, request, msg)
def get_resource_response(gadgetlist, format, items, user): """Obtains all the information related to a gadget encoded in the properly format (json or xml).""" if format == 'json' or format == 'default': gadgetresource = { 'resourceList': [ get_gadgetresource_data(resource, user) for resource in gadgetlist ] } response = HttpResponse(json_encode(gadgetresource), mimetype='application/json; charset=UTF-8') response.__setitem__('items', items) return response elif format == 'xml': response = get_xml_description(gadgetlist, user) response = HttpResponse(response, mimetype='text/xml; charset=UTF-8') response.__setitem__('items', items) return response else: return HttpResponseServerError( get_xml_error( _("Invalid format. Format must be either xml or json")), mimetype='application/xml; charset=UTF-8')
class PaymentAccountCollection(Resource): def read(self, request, user_name=None): user = get_user_authentication(request) user_wallet = None try: user_wallet = Wallet.objects.get(auth_user=user) except Exception, e: return HttpResponseServerError( get_xml_error(unicode(e)), mimetype='application/xml; charset=UTF-8') accounts = None try: accounts = Account.objects.filter() for account in accounts: account.form_html = account.form_html.replace( "{account_id}", str(account.id)) account.form_html = account.form_html.replace( "{wallet_id}", str(user_wallet.id)) account.form_html = account.form_html.replace( "{payment_account_title}", account.title) except Exception, e: return HttpResponseServerError( get_xml_error(_("No Payment Accounts")), mimetype='application/xml; charset=UTF-8')
class PaypalTransactionIPN(Resource): """ Registers a Payment transaction and updates the wallet balance """ def create(self, request, account_id=None, wallet_id=None): # Gets the attached wallet try: user_wallet = Wallet.objects.get(id=wallet_id) account = Account.objects.get(id=account_id) except Exception, e: log(e, request) return HttpResponseServerError( get_xml_error(_("Error getting objects")), mimetype='application/xml; charset=UTF-8') # Creates the transaction try: transaction = Transaction() transaction.wallet = user_wallet transaction.creation_date = datetime.now() transaction.transaction_type = 'R' transaction.concept = _('Wallet Recharge') transaction.amount = Decimal(request.POST.__getitem__("mc_gross")) if (request.POST.__getitem__("payment_status") == "Completed"): transaction.status = 'C' if (request.POST.__getitem__("payment_status") == "Pending"): transaction.status = 'P' transaction.gadget_pricing = None transaction.finish_date = transaction.creation_date transaction.payment_account = account transaction.save() except Exception, e: log(e, request) return HttpResponseServerError( get_xml_error(_("Error creating transaction")), mimetype='application/xml; charset=UTF-8')
except (HttpMethodNotAllowed, Http403): log_request(request, None, 'access') response = HttpResponseNotAllowed(self.permitted_methods) response.mimetype = self.mimetype return response except TracedServerError, e: log_request(request, None, 'access') msg = log_detailed_exception(request, e) except Exception, e: log_request(request, None, 'access') msg = log_exception(request, e) return HttpResponseServerError(get_xml_error(msg), mimetype='application/xml; charset=UTF-8') def adaptRequest(self, request): request._post, request._files = QueryDict(request.raw_post_data, encoding=request._encoding), datastructures.MultiValueDict() return request def dispatch(self, request, target, *args, **kwargs): request_method = request.method.upper() if request_method not in self.permitted_methods: raise HttpMethodNotAllowed if request_method == 'GET': return target.read(request, *args, **kwargs) elif request_method == 'POST': #PUT and DELETE request are wrapped in a POST request
class WorkSpacePublisherEntry(Resource): @transaction.commit_on_success def read(self, request, workspace_id): return self.create(request, workspace_id) @transaction.commit_on_success def create(self, request, workspace_id): if not request.REQUEST.has_key('data'): return HttpResponseBadRequest(get_xml_error(_("mashup data expected")), mimetype='application/xml; charset=UTF-8') received_json = request.REQUEST['data'] try: mashup = simplejson.loads(received_json) if not mashup.has_key('name'): raise Exception(_('Malformed mashup JSON: expecting mashup name.')) if not mashup.has_key('vendor'): raise Exception(_('Malformed mashup JSON: expecting mashup vendor.')) if not mashup.has_key('version'): raise Exception(_('Malformed mashup JSON: expecting mashup version.')) except Exception, e: transaction.rollback() msg = _("mashup cannot be published: ") + unicode(e) log(msg, request) return HttpResponseServerError(get_xml_error(msg), mimetype='application/xml; charset=UTF-8') workspace = get_object_or_404(WorkSpace, id=workspace_id) user = get_user_authentication(request) packageCloner = PackageCloner() cloned_workspace = packageCloner.clone_tuple(workspace) #Genrating info of new workspace vendor = mashup.get('vendor') name = mashup.get('name') version = mashup.get('version') author = mashup.get('author') email = mashup.get('email') description = mashup.get('description') + " \n " +get_workspace_description(workspace) imageURI = mashup.get('imageURI') wikiURI = mashup.get('wikiURI') # set default values if the variable is empty if imageURI == "": imageURI = 'http://share.skype.com/sites/devzone/headshot_mashup.jpg' if wikiURI == "": wikiURI = 'http://trac.morfeo-project.org/trac/ezwebplatform/wiki/Mashup' if author == "": author = user.username try: cloned_workspace.active=False cloned_workspace.vendor = vendor cloned_workspace.name = name cloned_workspace.version = version cloned_workspace.author = author cloned_workspace.mail = email cloned_workspace.description = description cloned_workspace.imageURI = imageURI cloned_workspace.wikiURI = wikiURI cloned_workspace.save() published_workspace = PublishedWorkSpace(type='CLONED', workspace=cloned_workspace, author=author, mail=email, vendor=vendor, name=name, version=version, description=description, imageURI=imageURI, wikiURI=wikiURI) published_workspace.save() except IntegrityError, e: transaction.rollback() msg = _("mashup cannot be published: ") + "duplicated mashup" log(msg, request) return HttpResponseServerError(get_xml_error(msg), mimetype='application/xml; charset=UTF-8')
def create(self, request, user_name=None): """ Purchases one gadget using a GadgetPricing ID Checks if there is any active transaction and if there is enough balance in the user wallet. Creates a transaction and substract the amount from the wallet ballance """ user = get_user_authentication(request) # gets user wallet information user_wallet = Wallet.objects.get(auth_user=user) # gets gadget pricing information pricing_id = request.POST.__getitem__('pricing_id') pricing = GadgetPricing.objects.get(id=pricing_id) # First check: Is gadget purchased? active_transaction = self._check_purchased_gadget(user_wallet, pricing.gadget.short_name, pricing.gadget.vendor, pricing.gadget.version) if active_transaction == True: return HttpResponseServerError(get_xml_error(_("Gadget is currently purchased")), mimetype='application/xml; charset=UTF-8') if hasattr(settings,'AUTHENTICATION_SERVER_URL'): user = get_user_authentication(request) # Gets the current user categories via ezsteroids API user_categories = _user_categories_tuple(user) gadget_special_pricings = GadgetSpecialPricing.objects.filter(pricing__id=pricing.id) # Refines the special pricing for gadget_special_pricing in gadget_special_pricings: for user_category in user_categories: if user_category[0] == gadget_special_pricing.user_category : if(pricing.price > gadget_special_pricing.price) : pricing.price = gadget_special_pricing.price # Second check: Is there enough balance if pricing.price > user_wallet.current_balance: return HttpResponseServerError(get_xml_error(_("There is not enough balance")), mimetype='application/xml; charset=UTF-8') # creates the transaction transaction = Transaction() transaction.wallet = user_wallet transaction.creation_date = datetime.now() transaction.transaction_type = 'P' transaction.concept = _('Gadget purchasing') transaction.amount = pricing.price transaction.status = 'C' transaction.gadget_pricing = pricing if pricing.periodicity == "P": transaction.finish_date = transaction.creation_date else: if pricing.periodicity == "D": duration = timedelta(days=pricing.duration) if pricing.periodicity == "W": duration = timedelta(weeks=pricing.duration) if pricing.periodicity == "M": duration = timedelta(days=pricing.duration*30) if pricing.periodicity == "Y": duration = timedelta(days=pricing.duration*365) transaction.finish_date = transaction.creation_date + duration #transaction.payment_item = 0 transaction.save() # Updates the user wallet user_wallet.current_balance -= pricing.price user_wallet.outstanding_balance -= pricing.price user_wallet.save() # returns the affected information return HttpResponse(json_encode({ "wallet": user_wallet, "pricing": pricing, "transaction": transaction}), mimetype='application/json; charset=UTF-8')