Example #1
0
    def post_profile(self, request_dict):
        post_profile = request_dict['profile']

        profile_id = request_dict['params']['profileId']
        if not uri.validate_uri(profile_id):
            err_msg = 'Profile ID %s is not a valid URI' % profile_id
            raise ParamError(err_msg)

        p, created = AgentProfile.objects.get_or_create(profileId=profile_id,
                                                        agent=self.Agent)

        if created:
            p.json_profile = ast.literal_eval(post_profile)
            p.content_type = request_dict['headers']['CONTENT_TYPE']
            p.etag = etag.create_tag(post_profile)

            if 'headers' in request_dict and (
                    'updated' in request_dict['headers']
                    and request_dict['headers']['updated']):
                p.updated = request_dict['headers']['updated']
        else:
            orig_prof = ast.literal_eval(p.json_profile)
            post_profile = ast.literal_eval(post_profile)
            merged = '%s' % dict(orig_prof.items() + post_profile.items())
            p.json_profile = merged
            p.etag = etag.create_tag(merged)

        p.save()
Example #2
0
    def post_profile(self, request_dict):
        post_profile = request_dict['profile']

        profile_id = request_dict['params']['profileId']
        if not uri.validate_uri(profile_id):
            err_msg = 'Profile ID %s is not a valid URI' % profile_id
            raise ParamError(err_msg)

        p, created = AgentProfile.objects.get_or_create(profileId=profile_id,agent=self.Agent)
        
        if created:
            p.json_profile = post_profile
            p.content_type = request_dict['headers']['CONTENT_TYPE']
            p.etag = etag.create_tag(post_profile)

            if 'headers' in request_dict and ('updated' in request_dict['headers'] and request_dict['headers']['updated']):
                p.updated = request_dict['headers']['updated']
        else:
            orig_prof = ast.literal_eval(p.json_profile)
            post_profile = ast.literal_eval(post_profile)
            merged = '%s' % dict(orig_prof.items() + post_profile.items())
            p.json_profile = merged
            p.etag = etag.create_tag(merged)

        p.save()
Example #3
0
    def put_profile(self, request_dict):
        profile_id = request_dict['params']['profileId']
        if not uri.validate_uri(profile_id):
            err_msg = 'Profile ID %s is not a valid URI' % profile_id
            raise ParamError(err_msg)

        p, created = AgentProfile.objects.get_or_create(profileId=profile_id,
                                                        agent=self.Agent)

        if request_dict['headers']['CONTENT_TYPE'] != "application/json":
            try:
                profile = ContentFile(request_dict['profile'].read())
            except:
                try:
                    profile = ContentFile(request_dict['profile'])
                except:
                    profile = ContentFile(str(request_dict['profile']))

            if not created:
                etag.check_preconditions(request_dict, p, required=True)
                p.profile.delete()
            self.save_profile(p, created, profile, request_dict)
        else:
            if not created:
                etag.check_preconditions(request_dict, p, required=True)
            the_profile = request_dict['profile']
            p.json_profile = ast.literal_eval(the_profile)
            p.content_type = request_dict['headers']['CONTENT_TYPE']
            p.etag = etag.create_tag(the_profile)

            if 'headers' in request_dict and (
                    'updated' in request_dict['headers']
                    and request_dict['headers']['updated']):
                p.updated = request_dict['headers']['updated']
            p.save()
Example #4
0
    def put_profile(self, request_dict):
        profile_id = request_dict['params']['profileId']
        if not uri.validate_uri(profile_id):
            err_msg = 'Profile ID %s is not a valid URI' % profile_id
            raise ParamError(err_msg)

        p,created = AgentProfile.objects.get_or_create(profileId=profile_id,agent=self.Agent)

        if request_dict['headers']['CONTENT_TYPE'] != "application/json":
            try:
                profile = ContentFile(request_dict['profile'].read())
            except:
                try:
                    profile = ContentFile(request_dict['profile'])
                except:
                    profile = ContentFile(str(request_dict['profile']))
        

            if not created:
                etag.check_preconditions(request_dict,p, required=True)
                p.profile.delete()
            self.save_profile(p, created, profile, request_dict)
        else:
            if not created:
                etag.check_preconditions(request_dict, p, required=True)
            the_profile = request_dict['profile']
            p.json_profile = the_profile
            p.content_type = request_dict['headers']['CONTENT_TYPE']
            p.etag = etag.create_tag(the_profile)

            if 'headers' in request_dict and ('updated' in request_dict['headers'] and request_dict['headers']['updated']):
                p.updated = request_dict['headers']['updated']
            p.save()
Example #5
0
    def post_profile(self, request_dict):
        post_profile = request_dict["profile"]

        profile_id = request_dict["params"]["profileId"]
        if not uri.validate_uri(profile_id):
            err_msg = "Profile ID %s is not a valid URI" % profile_id
            raise ParamError(err_msg)

        # get / create  profile
        p, created = models.ActivityProfile.objects.get_or_create(
            activityId=request_dict["params"]["activityId"], profileId=request_dict["params"]["profileId"]
        )

        if created:
            p.json_profile = post_profile
            p.content_type = request_dict["headers"]["CONTENT_TYPE"]
            p.etag = etag.create_tag(post_profile)

            # Set updated
            if "headers" in request_dict and (
                "updated" in request_dict["headers"] and request_dict["headers"]["updated"]
            ):
                p.updated = request_dict["headers"]["updated"]
        else:
            orig_prof = ast.literal_eval(p.json_profile)
            post_profile = ast.literal_eval(post_profile)
            # json.dumps changes the format of the string rep of the dict
            merged = "%s" % dict(orig_prof.items() + post_profile.items())
            p.json_profile = merged
            p.etag = etag.create_tag(merged)

        p.save()
Example #6
0
    def post_profile(self, request_dict):
        post_profile = request_dict['profile']

        profile_id = request_dict['params']['profileId']
        if not uri.validate_uri(profile_id):
            err_msg = 'Profile ID %s is not a valid URI' % profile_id
            raise ParamError(err_msg)

        # get / create  profile
        p, created = models.ActivityProfile.objects.get_or_create(
            activityId=request_dict['params']['activityId'],
            profileId=request_dict['params']['profileId'])

        if created:
            p.json_profile = post_profile
            p.content_type = request_dict['headers']['CONTENT_TYPE']
            p.etag = etag.create_tag(post_profile)

            #Set updated
            if 'headers' in request_dict and (
                    'updated' in request_dict['headers']
                    and request_dict['headers']['updated']):
                p.updated = request_dict['headers']['updated']
        else:
            orig_prof = ast.literal_eval(p.json_profile)
            post_profile = ast.literal_eval(post_profile)
            # json.dumps changes the format of the string rep of the dict
            merged = '%s' % dict(orig_prof.items() + post_profile.items())
            p.json_profile = merged
            p.etag = etag.create_tag(merged)

        p.save()
Example #7
0
    def clean(self):
        from lrs.util import uri
        if self.mbox != '' and not uri.validate_email(self.mbox):
            raise ValidationError('mbox value [%s] did not start with mailto:' % self.mbox)

        if self.openID != '' and not uri.validate_uri(self.openID):
            raise ValidationError('openID value [%s] is not a valid URI' % self.openID)            
Example #8
0
def validate_attachments(attachment_data, payload_sha2s):
    # For each attachment that is in the actual statement
    if isinstance(attachment_data, list):
        for attachment in attachment_data:
            # If display is not in the attachment it fails
            if not 'display' in attachment:
                err_msg = "Attachment must contain display property"
                raise ParamError(err_msg)

            # If the attachment data has a sha2 field, must validate it against the payload data
            if 'sha2' in attachment:
                sha2 = attachment['sha2']
                # Check if the sha2 field is a key in the payload dict
                if not sha2 in payload_sha2s:
                    err_msg = "Could not find attachment payload with sha: %s" % sha2
                    raise ParamError(err_msg)
            # If sha2 is not in the attachment and neither is fileURL, that is invalid 
            elif not 'fileUrl' in attachment:
                    err_msg = "Attachment did not contain a sha2 and did not contain a fileUrl"
                    raise ParamError(err_msg)
            # If sha2 is not in the attachment but fileUrl and has an empty value, that is invalid
            elif 'fileUrl' in attachment:
                if not attachment['fileUrl']:
                    err_msg = "Attachment had no value for fileUrl"
                    raise ParamError(err_msg)
                if not uri.validate_uri(attachment['fileUrl']):
                    err_msg = 'fileUrl %s is not a valid URI' % attachment['fileUrl']
                    raise ParamError(err_msg)
    else:
        err_msg = "attachments value type must be an array"
        raise ParamError(err_msg)
Example #9
0
    def saveContextToDB(self, context, contextExts):
        # Set context activities to context dict
        con_act_data = None
        if 'contextActivities' in context:
            con_act_data = context['contextActivities']
            del context['contextActivities']

        # Set context statement
        cs = None
        if 'cntx_statement' in context:
            cs = context['cntx_statement'] 
            del context['cntx_statement']
        
        # Save context
        cntx = models.context(content_object=self.model_object, **context)    
        cntx.save()

        # Set context in context statement and save
        if cs:
            cs.context = cntx
            cs.save()

        # Save context activities
        if con_act_data:
            for con_act in con_act_data.items():
                ca_id = con_act[1]['id']
                if not uri.validate_uri(ca_id):
                    raise exceptions.ParamError('Context Activity ID %s is not a valid URI' % ca_id)
                ca = models.ContextActivity(key=con_act[0], context_activity=ca_id, context=cntx)
                ca.save()
            cntx.save()

        # Save context extensions
        if contextExts:
            for k, v in contextExts.items():
                if not uri.validate_uri(k):
                    err_msg = "Extension ID %s is not a valid URI" % k
                    log_message(self.log_dict, err_msg, __name__, self.saveContextToDB.__name__, True)
                    update_parent_log_status(self.log_dict, 400)
                    raise exceptions.ParamError(err_msg)                    
                conExt = models.extensions(key=k, value=v, content_object=cntx)
                conExt.save()

        log_message(self.log_dict, "Context saved to database", __name__, self.saveContextToDB.__name__)

        return cntx        
Example #10
0
    def populate_extensions(self, act_def):
        for k, v in act_def['extensions'].items():
            if not uri.validate_uri(k):
                err_msg = "Extension ID %s is not a valid URI" % k
                raise exceptions.ParamError(err_msg)

            act_def_ext = models.ActivityDefinitionExtensions.objects.create(key=k, value=v,
                act_def=self.Activity.activitydefinition)
Example #11
0
    def clean(self):
        from lrs.util import uri

        if self.mbox and not uri.validate_email(self.mbox):
            raise ValidationError('mbox value [%s] did not start with mailto:' % self.mbox)

        if self.openID and not uri.validate_uri(self.openID):
            raise ValidationError('openID value [%s] is not a valid URI' % self.openID)            
Example #12
0
    def populate_extensions(self, act_def):
        for k, v in act_def['extensions'].items():
            if not uri.validate_uri(k):
                err_msg = "Extension ID %s is not a valid URI" % k
                log_message(self.log_dict, err_msg, __name__, self.populate_extensions.__name__, True) 
                update_parent_log_status(self.log_dict, 400)                   
                raise exceptions.ParamError(err_msg)

            act_def_ext = models.extensions(key=k, value=v,
                content_object=self.activity.activity_definition)
            act_def_ext.save()    
Example #13
0
    def __init__(self, request_dict, log_dict=None):        
        if not uri.validate_uri(request_dict['params']['activityId']):
            err_msg = 'Activity ID %s is not a valid URI' % request_dict['params']['activityId']       
            raise ParamError(err_msg)

        self.req_dict = request_dict
        self.agent = request_dict['params']['agent']
        self.activity_id = request_dict['params']['activityId']
        self.registration = request_dict['params'].get('registration', None)
        self.stateId = request_dict['params'].get('stateId', None)
        self.updated = request_dict['headers'].get('updated', None)
        self.content_type = request_dict['headers'].get('CONTENT_TYPE', None)
        self.state = request_dict.get('state', None)
        self.etag = request_dict.get('ETAG', None)
        self.since = request_dict['params'].get('since', None)
Example #14
0
    def __init__(self, request_dict, log_dict=None):
        if not uri.validate_uri(request_dict['params']['activityId']):
            err_msg = 'Activity ID %s is not a valid URI' % request_dict[
                'params']['activityId']
            raise ParamError(err_msg)

        self.req_dict = request_dict
        self.agent = request_dict['params']['agent']
        self.activity_id = request_dict['params']['activityId']
        self.registration = request_dict['params'].get('registration', None)
        self.stateId = request_dict['params'].get('stateId', None)
        self.updated = request_dict['headers'].get('updated', None)
        self.content_type = request_dict['headers'].get('CONTENT_TYPE', None)
        self.state = request_dict.get('state', None)
        self.etag = request_dict.get('ETAG', None)
        self.since = request_dict['params'].get('since', None)
Example #15
0
    def populate(self, the_object):        
        #Must include activity_id - set object's activity_id
        try:
            activity_id = the_object['id']
            if not uri.validate_uri(activity_id):
                raise exceptions.ParamError('Activity ID %s is not a valid URI' % activity_id)
        except KeyError:
            err_msg = "No id provided, must provide 'id' field"
            log_message(self.log_dict, err_msg, __name__, self.populate.__name__, True) 
            update_parent_log_status(self.log_dict, 400)          
            raise exceptions.ParamError(err_msg)

        # If allowed to define activities-create or get the global version
        if self.define:
            self.activity, act_created = models.activity.objects.get_or_create(activity_id=activity_id,
                global_representation=True)
        else:
            # Not allowed to create global version b/c don't have define permissions
            self.activity = models.activity(activity_id=activity_id, global_representation=False)
            self.activity.save()
            act_created = False
        if act_created: 
            log_message(self.log_dict, "Populating Activity - created Activity in database", __name__, self.populate.__name__)            
            if self.auth:
                self.activity.authoritative = self.auth
                self.activity.save()
        else:
            log_message(self.log_dict, "Populating Activity - retrieved Activity from database", __name__, self.populate.__name__)            

        valid_schema = False
        xml_data = {}
        
        #Try to grab XML from ID if no other JSON is provided - since it won't have a definition it's not a link
        #therefore it can be allowed to not resolve and will just return an empty dictionary
        if not 'definition' in the_object.keys():
            xml_data = self.validateID(activity_id)

            #If the ID validated against the XML schema then proceed with populating the definition with the info
            #from the XML - else just save the activity (someone sent in an ID that doesn't resolve and an objectType
            #with no other data)                
            if xml_data:
                self.populate_definition(xml_data, act_created)
        
        #Definition is provided
        else:
            self.validate_definition(the_object, act_created)
Example #16
0
    def build_verb_object(self, incoming_verb):
        log_message(self.log_dict, "Building verb object", __name__, self.build_verb_object.__name__)

        verb = {}    
        # Must have an ID
        if 'id' not in incoming_verb:
            err_msg = "ID field is not included in statement verb"
            log_message(self.log_dict, err_msg, __name__, self.build_verb_object.__name__, True) 
            update_parent_log_status(self.log_dict, 400)       
            raise exceptions.ParamError(err_msg)

        if not uri.validate_uri(incoming_verb['id']):
            err_msg = 'Verb ID %s is not a valid URI' % incoming_verb['id']
            log_message(self.log_dict, err_msg, __name__, self.build_verb_object.__name__, True) 
            update_parent_log_status(self.log_dict, 400)       
            raise exceptions.ParamError(err_msg)

        # Get or create the verb
        verb_object, created = models.Verb.objects.get_or_create(verb_id=incoming_verb['id'])

        # If existing, get existing keys
        if not created:
            existing_lang_map_keys = verb_object.display.all().values_list('key', flat=True)
        else:
            existing_lang_map_keys = []

        # Save verb displays
        if 'display' in incoming_verb:
            # Iterate incoming lang maps
            for verb_lang_map in incoming_verb['display'].items():
                # Make sure it's a tuple
                if isinstance(verb_lang_map, tuple):
                    # If incoming key doesn't already exist in verb's lang maps - add it
                    if not verb_lang_map[0] in existing_lang_map_keys: 
                        lang_map = self.save_lang_map(verb_lang_map, verb_object)    
                    else:
                        existing_verb_lang_map = verb_object.display.get(key=verb_lang_map[0])
                        models.LanguageMap.objects.filter(id=existing_verb_lang_map.id).update(value=verb_lang_map[1])
                else:
                    err_msg = "Verb display for verb %s is not a correct language map" % incoming_verb['id']
                    log_message(self.log_dict, err_msg, __name__, self.build_verb_object.__name__, True) 
                    update_parent_log_status(self.log_dict, 400)       
                    raise exceptions.ParamError(err_msg)
            verb_object.save()

        return verb_object
Example #17
0
    def create_agent(self, kwargs, define): 
        if 'account' in kwargs:
            account = kwargs['account']
            if 'homePage' in account:
                from lrs.util import uri
                if not uri.validate_uri(account['homePage']):
                    raise ValidationError('homePage value [%s] is not a valid URI' % account['homePage'])
                kwargs['account_homePage'] = kwargs['account']['homePage']

            if 'name' in account:
                kwargs['account_name'] = kwargs['account']['name']
            del kwargs['account']

        if not define:
            kwargs['global_representation'] = False
        ret_agent = Agent(**kwargs)
        ret_agent.full_clean(exclude=['subclass'])
        ret_agent.save()
        return ret_agent, True
Example #18
0
    def populate(self, the_object):        
        allowed_fields = ["objectType", "id", "definition"]
        failed_list = [x for x in the_object.keys() if not x in allowed_fields]
        if failed_list:
            err_msg = "Invalid field(s) found in activity - %s" % ', '.join(failed_list)
            raise exceptions.ParamError(err_msg)

        # Must include activity_id - set object's activity_id
        # Make sure it's a URI
        try:
            activity_id = the_object['id']
            if not uri.validate_uri(activity_id):
                raise exceptions.ParamError('Activity ID %s is not a valid URI' % activity_id)
        except KeyError:
            err_msg = "No id provided, must provide 'id' field"
            raise exceptions.ParamError(err_msg)

        # If allowed to define activities-create or get the global version
        if self.define:
            self.Activity, act_created = models.Activity.objects.get_or_create(activity_id=activity_id,
                global_representation=True)
        else:
            # Not allowed to create global version b/c don't have define permissions
            self.Activity = models.Activity.objects.create(activity_id=activity_id, global_representation=False)
            act_created = False

        if act_created:
            if self.auth:
                self.Activity.authoritative = self.auth
                self.Activity.save()

        # Try grabbing any activity data from the activity ID
        activity_definition = self.get_data_from_act_id(activity_id)

        # If there is a definition in the payload, grab it and merge with any data from activity ID
        # (payload data overrides ID data)
        if 'definition' in the_object:
            data_from_payload = the_object['definition']
            activity_definition = dict(activity_definition.items() + data_from_payload.items())

        # If there is a definition-populate the definition
        if activity_definition:
            self.populate_definition(activity_definition, act_created)
Example #19
0
    def put_profile(self, request_dict):
        try:
            profile = ContentFile(request_dict['profile'].read())
        except:
            try:
                profile = ContentFile(request_dict['profile'])
            except:
                profile = ContentFile(str(request_dict['profile']))
        
        profile_id = request_dict['params']['profileId']
        if not uri.validate_uri(profile_id):
            err_msg = 'Profile ID %s is not a valid URI' % profile_id
            raise ParamError(err_msg)

        p,created = AgentProfile.objects.get_or_create(profileId=profile_id,agent=self.Agent)
        if not created:
            etag.check_preconditions(request_dict,p, required=True)
            p.profile.delete()
        self.save_profile(p, created, profile, request_dict)
Example #20
0
    def post_profile(self, request_dict):
        post_profile = request_dict['profile']

        profile_id = request_dict['params']['profileId']
        if not uri.validate_uri(profile_id):
            err_msg = 'Profile ID %s is not a valid URI' % profile_id
            raise ParamError(err_msg)

        p, created = AgentProfile.objects.get_or_create(profileId=profile_id,agent=self.Agent)
        if created:
            profile = ContentFile(post_profile)
        else:
            original_profile = json.load(p.profile)
            post_profile = json.loads(post_profile)
            merged = dict(original_profile.items() + post_profile.items())
            p.profile.delete()
            profile = ContentFile(json.dumps(merged))

        self.save_profile(p, created, profile, request_dict)
Example #21
0
    def put_profile(self, request_dict):
        #Parse out profile from request_dict
        profile_id = request_dict['params']['profileId']
        if not uri.validate_uri(profile_id):
            err_msg = 'Profile ID %s is not a valid URI' % profile_id
            raise ParamError(err_msg)

        #Get the profile, or if not already created, create one
        p, created = models.ActivityProfile.objects.get_or_create(
            profileId=profile_id,
            activityId=request_dict['params']['activityId'])

        if request_dict['headers']['CONTENT_TYPE'] != "application/json":
            try:
                profile = ContentFile(request_dict['profile'].read())
            except:
                try:
                    profile = ContentFile(request_dict['profile'])
                except:
                    profile = ContentFile(str(request_dict['profile']))

            if not created:
                #If it already exists delete it
                etag.check_preconditions(request_dict, p, required=True)
                if p.profile:
                    p.profile.delete()

            self.save_profile(p, created, profile, request_dict)
        else:
            if not created:
                etag.check_preconditions(request_dict, p, required=True)
            the_profile = request_dict['profile']
            p.json_profile = the_profile
            p.content_type = request_dict['headers']['CONTENT_TYPE']
            p.etag = etag.create_tag(the_profile)

            #Set updated
            if 'headers' in request_dict and (
                    'updated' in request_dict['headers']
                    and request_dict['headers']['updated']):
                p.updated = request_dict['headers']['updated']
            p.save()
Example #22
0
    def put_profile(self, request_dict):
        # Parse out profile from request_dict
        profile_id = request_dict["params"]["profileId"]
        if not uri.validate_uri(profile_id):
            err_msg = "Profile ID %s is not a valid URI" % profile_id
            raise ParamError(err_msg)

        # Get the profile, or if not already created, create one
        p, created = models.ActivityProfile.objects.get_or_create(
            profileId=profile_id, activityId=request_dict["params"]["activityId"]
        )

        if request_dict["headers"]["CONTENT_TYPE"] != "application/json":
            try:
                profile = ContentFile(request_dict["profile"].read())
            except:
                try:
                    profile = ContentFile(request_dict["profile"])
                except:
                    profile = ContentFile(str(request_dict["profile"]))

            if not created:
                # If it already exists delete it
                etag.check_preconditions(request_dict, p, required=True)
                if p.profile:
                    p.profile.delete()

            self.save_profile(p, created, profile, request_dict)
        else:
            if not created:
                etag.check_preconditions(request_dict, p, required=True)
            the_profile = request_dict["profile"]
            p.json_profile = the_profile
            p.content_type = request_dict["headers"]["CONTENT_TYPE"]
            p.etag = etag.create_tag(the_profile)

            # Set updated
            if "headers" in request_dict and (
                "updated" in request_dict["headers"] and request_dict["headers"]["updated"]
            ):
                p.updated = request_dict["headers"]["updated"]
            p.save()
Example #23
0
    def saveResultToDB(self, result, resultExts):
        # Save the result with all of the args
        sc = result.pop('score', None)
        rslt = models.result(content_object=self.model_object, **result)
        rslt.save()
        if sc:
            sc.result = rslt
            sc.save()

        #If it has extensions, save them all
        if resultExts:
            for k, v in resultExts.items():
                if not uri.validate_uri(k):
                    err_msg = "Extension ID %s is not a valid URI" % k
                    log_message(self.log_dict, err_msg, __name__, self.saveResultToDB.__name__, True)
                    update_parent_log_status(self.log_dict, 400)
                    raise exceptions.ParamError(err_msg)
                resExt = models.extensions(key=k, value=v, content_object=rslt)
                resExt.save()
        log_message(self.log_dict, "Result saved to database", __name__, self.saveResultToDB.__name__)
        return rslt
Example #24
0
    def build_verb_object(self, incoming_verb):
        verb = {}    
        # Must have an ID
        if 'id' not in incoming_verb:
            err_msg = "ID field is not included in statement verb"
            raise exceptions.ParamError(err_msg)
        
        verb_id = incoming_verb['id']
        if not uri.validate_uri(verb_id):
            err_msg = 'Verb ID %s is not a valid URI' % verb_id
            raise exceptions.ParamError(err_msg)

        # Get or create the verb
        verb_object, created = models.Verb.objects.get_or_create(verb_id=verb_id)

        # If existing, get existing keys
        if not created:
            existing_lang_map_keys = verb_object.verbdisplay_set.all().values_list('key', flat=True)
        else:
            existing_lang_map_keys = []

        # Save verb displays
        if 'display' in incoming_verb:
            # Iterate incoming lang maps
            for verb_lang_map in incoming_verb['display'].items():
                # Make sure it's a tuple
                if isinstance(verb_lang_map, tuple):
                    # If incoming key doesn't already exist in verb's lang maps - add it
                    if not verb_lang_map[0] in existing_lang_map_keys: 
                        lang_map = self.save_lang_map(verb_lang_map, verb_object)    
                    else:
                        existing_verb_lang_map = verb_object.verbdisplay_set.get(key=verb_lang_map[0])
                        existing_verb_lang_map.value = verb_lang_map[1]
                        existing_verb_lang_map.save()
                else:
                    err_msg = "Verb display for verb %s is not a correct language map" % verb_id
                    raise exceptions.ParamError(err_msg)
            verb_object.save()

        return verb_object
Example #25
0
    def post_profile(self, request_dict):
        post_profile = request_dict['profile']
        
        profile_id = request_dict['params']['profileId']
        if not uri.validate_uri(profile_id):
            err_msg = 'Profile ID %s is not a valid URI' % profile_id      
            raise ParamError(err_msg)

        # get / create  profile
        p, created = models.ActivityProfile.objects.get_or_create(activityId=request_dict['params']['activityId'],  profileId=request_dict['params']['profileId'])
        if created:
            profile = ContentFile(post_profile)
        else:
            #   merge, update hash, save
            original_profile = json.load(p.profile)
            post_profile = json.loads(post_profile)
            merged = dict(original_profile.items() + post_profile.items())
            # delete original one
            p.profile.delete()
            # update
            profile = ContentFile(json.dumps(merged))

        self.save_profile(p, created, profile, request_dict)
Example #26
0
    def put_profile(self, request_dict):
        #Parse out profile from request_dict
        try:
            profile = ContentFile(request_dict['profile'].read())
        except:
            try:
                profile = ContentFile(request_dict['profile'])
            except:
                profile = ContentFile(str(request_dict['profile']))

        profile_id = request_dict['params']['profileId']
        if not uri.validate_uri(profile_id):
            err_msg = 'Profile ID %s is not a valid URI' % profile_id
            raise ParamError(err_msg)

        #Get the profile, or if not already created, create one
        p,created = models.ActivityProfile.objects.get_or_create(profileId=request_dict['params']['profileId'],activityId=request_dict['params']['activityId'])
        
        if not created:
            #If it already exists delete it
            etag.check_preconditions(request_dict,p, required=True)
            p.profile.delete()
        
        self.save_profile(p, created, profile, request_dict)
Example #27
0
 def handle_account(self, val, kwargs, members, define):
     # Load into dict if necessary
     if not isinstance(val, dict):
         account = json.loads(val)
     else:
         account = val
     # Try to get the account with the account kwargs. If it exists set ret_agent to the account's
     # agent and created to false. Update agent if necessary
     try:
         if 'homePage' in account:
             from lrs.util import uri
             if not uri.validate_uri(account['homePage']):
                 raise ValidationError('homePage value [%s] is not a valid URI' % account['homePage'])
         acc = AgentAccount.objects.get(**account)
         created = False
         ret_agent = acc.agent
         ret_agent, need_to_create = self.update_agent_name_and_members(kwargs, ret_agent, members, define)
         if need_to_create:
             ret_agent, created = self.create_agent(kwargs, define)        
     except AgentAccount.DoesNotExist:
         # If account doesn't exist try to get agent with the remaining kwargs (don't need
         # attr_dict) since IFP is account which doesn't exist yet
         try:
             ret_agent = Agent.objects.get(**kwargs)     
         except Agent.DoesNotExist:
             # If agent/group does not exist, create, clean, save it and create an account
             # to attach to it. Created account is true. If don't have define permissions
             # then the agent/group is non-global
             if not define:
                 kwargs['global_representation'] = False
             ret_agent = Agent(**kwargs)
         ret_agent.full_clean(exclude=['subclass', 'content_type', 'content_object', 'object_id'])
         ret_agent.save()
         acc = AgentAccount.objects.create(agent=ret_agent, **account)
         created = True
     return ret_agent, created
Example #28
0
    def populate_definition(self, act_def, act_created):
        allowed_fields = ['name', 'description', 'type', 'moreInfo', 'extensions', 'interactionType',
        'correctResponsesPattern', 'choices', 'scale', 'source', 'target', 'steps']

        failed_list = [x for x in act_def.keys() if not x in allowed_fields]
        if failed_list:
            err_msg = "Invalid field(s) found in activity definition - %s" % ', '.join(failed_list)
            raise exceptions.ParamError(err_msg)

        # only update existing def stuff if request has authority to do so
        if not act_created and (self.Activity.authoritative != '' and self.Activity.authoritative != self.auth):
            err_msg = "This ActivityID already exists, and you do not have the correct authority to create or update it."
            raise exceptions.Forbidden(err_msg)

        # validate type if it exists
        act_def_type = ''
        if 'type' in act_def:
            act_def_type = act_def['type']
            if not uri.validate_uri(act_def_type):
                raise exceptions.ParamError('Activity definition type %s is not a valid URI' % act_def_type)
        
            #If the type is cmi.interaction, have to check interactionType
            interaction_flag = None
            if act_def_type == 'http://adlnet.gov/expapi/activities/cmi.interaction':
                interaction_flag = self.validate_cmi_interaction(act_def, act_created)

        # validate moreInfo if it exists
        if 'moreInfo' in act_def:
            moreInfo = act_def['moreInfo']
            if not uri.validate_uri(moreInfo):
                raise exceptions.ParamError('moreInfo %s is not a valid URI' % moreInfo)
        else:
            moreInfo = ''

        # return t/f if you can create the def from type, interactionType and moreInfo if the activity already
        # doesn't have a definition
        act_def_created = self.save_activity_definition_to_db(act_def_type, act_def.get('interactionType', ''),
            moreInfo)

        # If the activity had already existed and lrs auth is off or user has authority to update it
        if not act_created: 
            if self.Activity.authoritative == '' or self.Activity.authoritative == self.auth:
                # Update name and desc if needed
                self.update_activity_name_and_description(act_def, self.Activity)
            else:
                err_msg = "This ActivityID already exists, and you do not have the correct authority to create or update it."
                raise exceptions.Forbidden(err_msg)
        # Else the activity was newly created
        else:
            # If created and have permisson to (re)define activities
            if self.define:
                # Save activity definition names and descriptions
                if 'name' in act_def:
                    for name_lang_map in act_def['name'].items():
                        if isinstance(name_lang_map, tuple):
                            n = models.ActivityDefNameLangMap.objects.create(key=name_lang_map[0],
                                          value=name_lang_map[1],
                                          act_def=self.Activity.activitydefinition)
                        else:
                            err_msg = "Activity with id %s has a name that is not a valid language map" % self.Activity.activity_id
                            raise exceptions.ParamError(err_msg)

                if 'description' in act_def:
                    for desc_lang_map in act_def['description'].items():
                        if isinstance(desc_lang_map, tuple):
                            d = models.ActivityDefDescLangMap.objects.create(key=desc_lang_map[0],
                                          value=desc_lang_map[1],
                                          act_def=self.Activity.activitydefinition)
                        else:
                            err_msg = "Activity with id %s has a description that is not a valid language map" % self.Activity.activity_id
                            raise exceptions.ParamError(err_msg)
        
        # If the activity definition was just created (can't update the CRP or extensions of a def if already existed)
        #If there is a correctResponsesPattern then save the pattern
        if act_def_created and 'correctResponsesPattern' in act_def.keys():
            if isinstance(act_def['correctResponsesPattern'], list):
                self.populate_correctResponsesPattern(act_def, interaction_flag)
            else:
                err_msg = "correctResponsesPattern value type must be an array"
                raise exceptions.ParamError(err_msg)
        #See if activity definition has extensions
        if act_def_created and 'extensions' in act_def.keys():
            self.populate_extensions(act_def) 
Example #29
0
        sc = result.pop('score', None)
        try:
            rslt = models.Result.objects.create(**result)
        except TypeError, e:
            err_msg = "Invalid field in result - %s" % e.message
            raise exceptions.ParamError(err_msg)

        # Set score if one
        if sc:
            sc.result = rslt
            sc.save()

        #If it has extensions, save them all
        if resultExts:
            for k, v in resultExts.items():
                if not uri.validate_uri(k):
                    err_msg = "Extension ID %s is not a valid URI" % k
                    raise exceptions.ParamError(err_msg)
                resExt = models.ResultExtensions.objects.create(key=k, value=v, result=rslt)
        return rslt

    def saveContextToDB(self, context, contextExts):
        # Set context activities to context dict
        con_act_data = None
        if 'contextActivities' in context:
            con_act_data = context['contextActivities']
            del context['contextActivities']

        # Save context stmt if one
        stmt_data = None
        if 'statement' in context: