def handle(self, *args, **options): # make sure file option is present if options['extract_event_number'] is None: extract_event_number = 100 else: extract_event_number = int(options['extract_event_number']) evt_list = TrackingLog.objects \ .filter(tincan_error='WRONG_VERB_OBJECT') \ .order_by('dtcreated')[:extract_event_number] for evt in evt_list: statement_json = json.loads(evt.statement) statement = { 'actor': Agent.from_json(json.dumps(statement_json['actor'])), 'verb': Verb.from_json(json.dumps(statement_json['verb'])), 'object': Activity.from_json(json.dumps(statement_json['object'])), 'timestamp': statement_json['timestamp'], 'context': Context.from_json(json.dumps(statement_json['context'])), } evt.statement = json.dumps(statement) evt.tincan_error = "CONVERTED" evt.save()
def test_setIdExceptionEmptyString(self): verb = Verb(id='test') with self.assertRaises(ValueError): verb.id = '' self.assertEqual(verb.id, 'test')
def test_ToJSONEmpty(self): verb = Verb() self.assertEqual(verb.to_json(), '{}')
def test_ToJSON(self): verb = Verb(**{"id": "test", "display": {"en-US": "test"}}) self.assertEqual(verb.to_json(), '{"id": "test", "display": {"en-US": "test"}}')
def test_AsVersionIgnoreNone(self): verb = Verb(display={'en-US': 'test'}) verb2 = verb.as_version() self.assertEqual(verb2, {'display': {'en-US': 'test'}})
def test_AsVersionNotEmpty(self): verb = Verb(id='test') verb2 = verb.as_version() self.assertEqual(verb2, {'id': 'test'})
def track_update_post(sender, post, user, request, response, **kwargs): """Log a XAPI statement when a user updates a post.""" consumer = getattr(user, "lti_consumer", None) if consumer is None: logger.warning("Unable to get LTI consumer of user %s", user) return xapi_logger = logging.getLogger(f"xapi.{user.lti_consumer.slug}") verb = Verb( id="https://w3id.org/xapi/dod-isd/verbs/updated", display=LanguageMap({"en-US": "updated"}), ) obj = Activity( id=f"id://ashley/post/{post.pk}", definition=ActivityDefinition( name=LanguageMap( {to_locale(settings.LANGUAGE_CODE).replace("_", "-"): post.subject} ), type="https://w3id.org/xapi/acrossx/activities/message", ), ) parent_activities = [ Activity( id=f"uuid://{post.topic.forum.lti_id}", definition=ActivityDefinition( name=LanguageMap( { to_locale(settings.LANGUAGE_CODE).replace( "_", "-" ): post.topic.subject } ), type="http://id.tincanapi.com/activitytype/discussion", ), ) ] if request.forum_permission_handler.current_lti_context_id is not None: try: lti_context = LTIContext.objects.get( pk=request.forum_permission_handler.current_lti_context_id ) parent_activities.append( Activity( id=lti_context.lti_id, definition=ActivityDefinition( type="http://adlnet.gov/expapi/activities/course" ), ) ) except LTIContext.DoesNotExist: pass context = Context( context_activities=ContextActivities(parent=parent_activities), ) statement = build_statement(user, verb, obj, context) if statement: xapi_logger.info(statement.to_json())
def test_FromJSONEmptyObject(self): verb = Verb.from_json('{}') self.assertIsNone(verb.id)
def socialmedia_builder(verb, platform, account_name, account_homepage, object_type, object_id, message, tags=[], parent_object_type=None, parent_id=None, rating=None, instructor_name=None, instructor_email=None, team_name=None, course_code=None, account_email=None, user_name=None, timestamp=None): verbmapper = {'created': 'http://activitystrea.ms/schema/1.0/create', 'shared': 'http://activitystrea.ms/schema/1.0/share', 'liked': 'http://activitystrea.ms/schema/1.0/like', 'rated': 'http://id.tincanapi.com/verb/rated', 'commented': 'http://adlnet.gov/expapi/verbs/commented'} objectmapper = {'Note': 'http://activitystrea.ms/schema/1.0/note', 'Tag': 'http://id.tincanapi.com/activitytype/tag', 'Article': 'http://activitystrea.ms/schema/1.0/article', 'Video': 'http://activitystrea.ms/schema/1.0/video'} agentaccount = AgentAccount(name=account_name, home_page=account_homepage) actor = Agent(account=agentaccount) if (account_email is not None): actor.mbox = account_email if (user_name is not None): actor.name = user_name verb_obj = Verb(id=verbmapper[verb],display=LanguageMap({'en-US': verb})) #message = message.decode('utf-8').encode('ascii', 'ignore') #message.decode('utf-8').replace(u"\u2018", "'").replace(u"\u2019", "'").replace(u"\u2013", "-").replace(u"\ud83d", " ").replace(u"\ude09", " ").replace(u"\u00a0l", " ").replace(u"\ud83d", " ").replace(u"\u2026", " ").replace(u"\ude09", " ").replace(u"\u00a0"," ") object = Activity( id=object_id, object_type=object_type, definition=ActivityDefinition( name=LanguageMap({'en-US': message}), type=objectmapper[object_type] ), ) taglist = [] for tag in tags: tagobject = Activity( id='http://id.tincanapi.com/activity/tags/tincan', object_type='Activity', definition=ActivityDefinition( name=LanguageMap({'en-US': tag}), type=objectmapper['Tag'] ), ) taglist.append(tagobject) parentlist = [] if (verb in ['liked','shared','commented','rated']): parentobject = Activity( id=parent_id, object_type=parent_object_type, ) parentlist.append(parentobject) courselist = [] if (course_code is not None): courseobject = Activity( id=course_code, object_type='Course', definition=ActivityDefinition(type="http://adlnet.gov/expapi/activities/course") ) courselist.append(courseobject) instructor = None if (instructor_name is not None): instructor=Agent(name=instructor_name,mbox=instructor_email) team = None if (team_name is not None): team = Group(Agent(name=team_name), object_type='Group') result = None if (rating is not None): rating_as_float = float(rating) result = Result(score=Score(raw=rating_as_float)) context = Context( registration=uuid.uuid4(), platform=platform, instructor=instructor, team=team, context_activities=ContextActivities(other=ActivityList(taglist),parent=ActivityList(parentlist),grouping=ActivityList(courselist)) ) statement = statement_builder(actor, verb_obj, object, context, result, timestamp) return statement
def sendStatement(self, reqData): #load requested data for statement generation data = json.loads(reqData) # create RemoteLRS endpoint lrs = self.LRS # generate statement # 1. actor actor = Agent( name=data["name"], mbox='mailto:' + data["name"] + '@id.lrs', ) # 2. verb verb = Verb( id=self.verbs.get(data["verb"]), display=LanguageMap({'en-US': data["verb"]}), ) # 3. object obj = Activity( id=self.objects.get(data["activity"]), definition=ActivityDefinition( name=LanguageMap({'en-US': data["activityid"]}) ) ) # 4. context context = Context( extensions=Extensions({ self.extensions.get("difficulty"): data["difficulty"], self.extensions.get("interaction"): data["interaction"], self.extensions.get("topic"): data["topic"] }) ) # 5. result result = Result( score=Score( raw=data["score"] ), success=data["success"] ) # build statement statement = Statement( actor=actor, verb=verb, object=obj, context=context, result=result ) # save statement response = lrs.save_statement(statement) # check response if not response: raise ValueError("statement failed to save") return str(True)
def test_FromJSONExceptionMalformedJSON(self): with self.assertRaises(AttributeError): verb = Verb.from_json('{"test": "invalid property"}')
def get_verb(self, event): return Verb( id=constants.XAPI_VERB_COMPLETED, display=LanguageMap({'en': 'completed'}), )
def get_verb(self, event): return Verb( id=constants.XAPI_VERB_ANSWERED, display=LanguageMap({'en-US': 'answered', 'ru-RU': 'дан ответ'}), )
def setUp(self): self.endpoint = lrs_properties.endpoint self.version = lrs_properties.version self.username = lrs_properties.username self.password = lrs_properties.password self.lrs = RemoteLRS( version=self.version, endpoint=self.endpoint, username=self.username, password=self.password, ) self.agent = Agent(mbox="mailto:[email protected]") self.agent2 = Agent(mbox="mailto:[email protected]") self.verb = Verb( id="http://adlnet.gov/expapi/verbs/experienced", display=LanguageMap({"en-US": "experienced"}) ) self.group = Group(member=[self.agent, self.agent2]) self.activity = Activity( id="http://tincanapi.com/TinCanPython/Test/Unit/0", definition=ActivityDefinition() ) self.activity.definition.type = "http://id.tincanapi.com/activitytype/unit-test" self.activity.definition.name = LanguageMap({"en-US": "Python Tests"}) self.activity.definition.description = LanguageMap( {"en-US": "Unit test in the test suite for the Python library"} ) self.activity.object_type = 'Activity' self.parent = Activity( id="http://tincanapi.com/TinCanPython/Test", definition=ActivityDefinition()) self.parent.definition.type = "http://id.tincanapi.com/activitytype/unit-test-suite" self.parent.definition.name = LanguageMap({"en-US": "Python Tests"}) self.parent.definition.description = LanguageMap( {"en-US": "Unit test in the test suite for the Python library"} ) self.parent.object_type = 'Activity' self.statement_ref = StatementRef(id=uuid.uuid4()) self.context = Context(registration=uuid.uuid4(), statement=self.statement_ref) # self.context.context_activities = ContextActivities(parent=[self.parent]) self.score = Score( raw=97, scaled=0.97, max=100, min=0 ) self.result = Result( score=self.score, success=True, completion=True, duration="PT120S" ) self.substatement = SubStatement( actor=self.agent, verb=self.verb, object=self.activity, )
def track_topic_view(sender, topic, user, request, response, **kwargs): """Log a XAPI statement when a user views a topic.""" consumer = getattr(user, "lti_consumer", None) if consumer is None: logger.warning("Unable to get LTI consumer of user %s", user) return xapi_logger = logging.getLogger(f"xapi.{user.lti_consumer.slug}") verb = Verb( id="http://id.tincanapi.com/verb/viewed", display=LanguageMap({"en-US": "viewed"}), ) obj = Activity( id=f"id://ashley/topic/{topic.pk}", definition=ActivityDefinition( name=LanguageMap( {to_locale(settings.LANGUAGE_CODE).replace("_", "-"): topic.subject} ), type="http://id.tincanapi.com/activitytype/discussion", extensions={ "https://w3id.org/xapi/acrossx/extensions/total-items": topic.posts_count, "https://w3id.org/xapi/acrossx/extensions/total-pages": ( (topic.posts_count - 1) // machina_settings.TOPIC_POSTS_NUMBER_PER_PAGE ) + 1, }, ), ) parent_activities = [ Activity( id=f"uuid://{topic.forum.lti_id}", definition=ActivityDefinition( name=LanguageMap( { to_locale(settings.LANGUAGE_CODE).replace( "_", "-" ): topic.forum.name } ), type="http://id.tincanapi.com/activitytype/community-site", ), ) ] if request.forum_permission_handler.current_lti_context_id is not None: try: lti_context = LTIContext.objects.get( pk=request.forum_permission_handler.current_lti_context_id ) parent_activities.append( Activity( id=lti_context.lti_id, definition=ActivityDefinition( type="http://adlnet.gov/expapi/activities/course" ), ) ) except LTIContext.DoesNotExist: pass context = Context( context_activities=ContextActivities(parent=parent_activities), extensions={ "http://www.risc-inc.com/annotator/extensions/page": int( request.GET.get("page", default=1) ) }, ) statement = build_statement(user, verb, obj, context) if statement: xapi_logger.info(statement.to_json())
def test_setDisplayExceptionNestedObject(self): verb = Verb(display=LanguageMap({"en-US": "test"})) with self.assertRaises(TypeError): verb.display = {"fr-CA": {"nested": "object"}} self.displayVerificationHelper(verb.display)
def test_FromJSONExceptionBadJSON(self): with self.assertRaises(ValueError): Verb.from_json('{"bad JSON"}')
def generate(cls, verb): if cls._validate_verb(verb): verb_id = cls.verbs.get(verb) return Verb(id=verb_id, display=LanguageMap({'en-US': verb})) return None
def test_FromJSONExceptionEmpty(self): with self.assertRaises(ValueError): Verb.from_json('')
def get_verb(self, event): return Verb( id=constants.XAPI_VERB_ANSWERED, display=LanguageMap({'en': 'answered'}), )
def test_AsVersionEmpty(self): verb = Verb() verb2 = verb.as_version() self.assertEqual(verb2, {})
def get_verb(self, event): return Verb( id=constants.XAPI_VERB_ATTEMPTED, display=LanguageMap({'en': 'attempted'}), )
def test_AsVersion(self): verb = Verb(id='test', display={'en-US': 'test'}) verb2 = verb.as_version() self.assertEqual(verb2, {'id': 'test', 'display': {'en-US': 'test'}})
def get_verb(self, event): return Verb( id=constants.XAPI_VERB_INITIALIZED, display=LanguageMap({'en': 'reset'}), )
def test_ToJSONFromJSON(self): json_str = '{"id": "test", "display": {"en-US": "test"}}' verb = Verb.from_json(json_str) self.assertEqual(verb.id, 'test') self.displayVerificationHelper(verb.display) self.assertEqual(verb.to_json(), json_str)
print "...done" #http://data.europa.eu/esco/occupation/00030d09-2b3a-4efd-87cc-c4ea39d27c34 # construct the actor of the statement print "constructing the Actor..." actor = Agent( name='UserMan', mbox='mailto:[email protected]', ) print "...done" # construct the verb of the statement print "constructing the Verb..." verb = Verb( id='http://adlnet.gov/expapi/verbs/experienced', display=LanguageMap({'en-US': 'experienced'}), ) print "...done" # construct the object of the statement print "constructing the Object..." object = Activity( id='http://data.europa.eu/esco/skill/fed5b267-73fa-461d-9f69-827c78beb39d', definition=ActivityDefinition( name=LanguageMap({'en-US': 'TinCanPython Library'}), description=LanguageMap( {'en-US': 'Use of, or interaction with, Shady Library'}), ), ) print "...done"
def test_ToJSONIgnoreNoneId(self): verb = Verb(display={"en-US": "test"}) self.assertEqual(verb.to_json(), '{"display": {"en-US": "test"}}')
def post(self, request, *args, **kwargs): result = None project_title = request.GET.get('ca_name', None) project_url = request.GET.get('ca_id', None) form = self.form_class(request.POST) date_time = request.POST.get('timestamp', '') print('date_time:', date_time) if form.is_valid(): # <process form cleaned data> data = form.cleaned_data if form.data.get('send', ''): actor = Agent(name=data['actor_name'], mbox='mailto:{}'.format(data['actor_email'])) verb_id = data['verb_id'] verb = Verb( id=verb_id, display=LanguageMap( **xapi_verbs_by_id[verb_id]['display']), ) object_language = data['object_language'] activity_definition = ActivityDefinition( name=LanguageMap(**{object_language: data['object_name']}), type=data['activity_type'], ) if data['object_description']: activity_definition.description = LanguageMap( **{object_language: data['object_description']}) object = Activity( id=make_uri(data['object_id']), definition=activity_definition, ) context = {'platform': data['platform']} if data['context_object_name'] and data['context_object_id']: context_activity_definition = ActivityDefinition( name=LanguageMap( **{object_language: data['context_object_name']}), type=data['context_activity_type'], ) context_activity_object = Activity( id=make_uri(data['context_object_id']), definition=context_activity_definition, ) context_activities = { data['context_activity_relationship']: context_activity_object } context['context_activities'] = context_activities """ authority = Agent( name=data['authority_name'], mbox='mailto:{}'.format(data['authority_email']) ) """ timestamp = data['timestamp'] print('timestamp 1:', timestamp) """ timestamp = datetime.strptime(date_time, "%d/%m/%Y %H:%M") print('timestamp 2:', timestamp) """ statement = Statement(actor=actor, verb=verb, object=object, context=context, timestamp=timestamp) result = send_statement(statement) recipe_ids = request.POST.getlist('recipe_ids') if recipe_ids: form.fields['verb_id'].choices = get_verb_choices(recipe_ids) form.fields['activity_type'].choices = get_activity_choices( recipe_ids) if result: try: result = json.dumps(json.loads(result.to_json()), indent=2) except: pass return render( request, self.template_name, { 'form': form, 'result': result, 'project_title': project_title, 'project_url': project_url })
def test_setId(self): verb = Verb(id='test') verb.id = 'newId' self.assertEqual(verb.id, 'newId')
debug_filepath = os.path.join(MrPythonConf.GetUserCfgDir(), 'tracing_debug.txt') session_filepath = os.path.join(MrPythonConf.GetUserCfgDir(), 'tracing_session.txt') # LRS properties lrs_endpoint = "https://lrsmocah.lip6.fr/data/xAPI" lrs_version = "1.0.1" # 1.0.1 | 1.0.0 | 0.95 | 0.9 lrs_username = "******" lrs_password = "******" proxy_name = "" proxy_port = 0 # xAPI verbs and activites verbs = { "opened": Verb( id="http://activitystrea.ms/schema/1.0/open", display=LanguageMap({'en-US': 'opened'})), "closed": Verb( id="http://activitystrea.ms/schema/1.0/close", display=LanguageMap({'en-US': 'closed'})), "created": Verb( id="http://activitystrea.ms/schema/1.0/create", display=LanguageMap({'en-US': 'created'})), "saved": Verb( id="http://activitystrea.ms/schema/1.0/save", display=LanguageMap({'en-US': 'saved'})), "saved-as": Verb( id="https://www.lip6.fr/mocah/invalidURI/verbs/save-as", display=LanguageMap({'en-US': 'saved as'})), "switched": Verb( id="https://www.lip6.fr/mocah/invalidURI/verbs/switched", display=LanguageMap({'en-US': 'switched'})), "started": Verb( id="http://activitystrea.ms/schema/1.0/start", display=LanguageMap({'en-US': 'started'})), "passed": Verb( id="http://adlnet.gov/expapi/verbs/passed", display=LanguageMap({'en-US': 'passed'})), "failed": Verb(
def test_setDisplay(self): verb = Verb(display=LanguageMap({"fr-CA": "not test"})) verb.display = {"en-US": "test"} self.assertIsNone(verb.id) self.displayVerificationHelper(verb.display)
def test_FromJSONId(self): verb = Verb.from_json('{"id": "test"}') self.assertEqual(verb.id, 'test')
def test_setDisplayExceptionBadMap(self): verb = Verb(display=LanguageMap({"en-US": "test"})) with self.assertRaises(ValueError): verb.display = {"bad map"} self.displayVerificationHelper(verb.display)
def test_FromJSONExceptionFlatDisplay(self): with self.assertRaises(ValueError): Verb.from_json('{"id": "test", "display": "flatdisplay"}')
def test_FromJSONExceptionPartiallyMalformedJSON(self): with self.assertRaises(AttributeError): Verb.from_json('{"test": "invalid property", "id": \ "valid property"}')
def test_FromJSONExceptionEmptyId(self): with self.assertRaises(ValueError): Verb.from_json('{"id":"''"}')
def test_FromJSON(self): verb = Verb.from_json('{"id": "test", "display": {"en-US": "test"}}') self.assertEqual(verb.id, 'test') self.displayVerificationHelper(verb.display)
def test_InitVerb(self): substatement = SubStatement(verb=Verb(id='test')) self.verbVerificationHelper(substatement.verb)