예제 #1
0
    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()
예제 #2
0
 def test_setIdExceptionEmptyString(self):
     verb = Verb(id='test')
     with self.assertRaises(ValueError):
         verb.id = ''
     self.assertEqual(verb.id, 'test')
예제 #3
0
 def test_ToJSONEmpty(self):
     verb = Verb()
     self.assertEqual(verb.to_json(), '{}')
예제 #4
0
 def test_ToJSON(self):
     verb = Verb(**{"id": "test", "display": {"en-US": "test"}})
     self.assertEqual(verb.to_json(), '{"id": "test", "display": {"en-US": "test"}}')
예제 #5
0
 def test_AsVersionIgnoreNone(self):
     verb = Verb(display={'en-US': 'test'})
     verb2 = verb.as_version()
     self.assertEqual(verb2, {'display': {'en-US': 'test'}})
예제 #6
0
 def test_AsVersionNotEmpty(self):
     verb = Verb(id='test')
     verb2 = verb.as_version()
     self.assertEqual(verb2, {'id': 'test'})
예제 #7
0
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())
예제 #8
0
 def test_FromJSONEmptyObject(self):
     verb = Verb.from_json('{}')
     self.assertIsNone(verb.id)
예제 #9
0
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
예제 #10
0
    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)
예제 #11
0
 def test_FromJSONExceptionMalformedJSON(self):
     with self.assertRaises(AttributeError):
         verb = Verb.from_json('{"test": "invalid property"}')
예제 #12
0
 def get_verb(self, event):
     return Verb(
         id=constants.XAPI_VERB_COMPLETED,
         display=LanguageMap({'en': 'completed'}),
     )
예제 #13
0
 def get_verb(self, event):
     return Verb(
         id=constants.XAPI_VERB_ANSWERED,
         display=LanguageMap({'en-US': 'answered', 'ru-RU': 'дан ответ'}),
     )
예제 #14
0
    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,
        )
예제 #15
0
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())
예제 #16
0
 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)
예제 #17
0
 def test_FromJSONExceptionBadJSON(self):
     with self.assertRaises(ValueError):
         Verb.from_json('{"bad JSON"}')
예제 #18
0
    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
예제 #19
0
 def test_FromJSONExceptionEmpty(self):
     with self.assertRaises(ValueError):
         Verb.from_json('')
예제 #20
0
 def get_verb(self, event):
     return Verb(
         id=constants.XAPI_VERB_ANSWERED,
         display=LanguageMap({'en': 'answered'}),
     )
예제 #21
0
 def test_AsVersionEmpty(self):
     verb = Verb()
     verb2 = verb.as_version()
     self.assertEqual(verb2, {})
예제 #22
0
 def get_verb(self, event):
     return Verb(
         id=constants.XAPI_VERB_ATTEMPTED,
         display=LanguageMap({'en': 'attempted'}),
     )
예제 #23
0
 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'}})
예제 #24
0
 def get_verb(self, event):
     return Verb(
         id=constants.XAPI_VERB_INITIALIZED,
         display=LanguageMap({'en': 'reset'}),
     )
예제 #25
0
 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)
예제 #26
0
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"
예제 #27
0
 def test_ToJSONIgnoreNoneId(self):
     verb = Verb(display={"en-US": "test"})
     self.assertEqual(verb.to_json(), '{"display": {"en-US": "test"}}')
예제 #28
0
 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
         })
예제 #29
0
 def test_setId(self):
     verb = Verb(id='test')
     verb.id = 'newId'
     self.assertEqual(verb.id, 'newId')
예제 #30
0
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(
예제 #31
0
 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)
예제 #32
0
 def test_FromJSONId(self):
     verb = Verb.from_json('{"id": "test"}')
     self.assertEqual(verb.id, 'test')
예제 #33
0
 def test_setDisplayExceptionBadMap(self):
     verb = Verb(display=LanguageMap({"en-US": "test"}))
     with self.assertRaises(ValueError):
         verb.display = {"bad map"}
     self.displayVerificationHelper(verb.display)
예제 #34
0
 def test_FromJSONExceptionFlatDisplay(self):
     with self.assertRaises(ValueError):
         Verb.from_json('{"id": "test", "display": "flatdisplay"}')
예제 #35
0
 def test_FromJSONExceptionPartiallyMalformedJSON(self):
     with self.assertRaises(AttributeError):
         Verb.from_json('{"test": "invalid property", "id": \
         "valid property"}')
예제 #36
0
 def test_FromJSONId(self):
     verb = Verb.from_json('{"id": "test"}')
     self.assertEqual(verb.id, 'test')
예제 #37
0
 def test_FromJSONExceptionEmptyId(self):
     with self.assertRaises(ValueError):
         Verb.from_json('{"id":"''"}')
예제 #38
0
 def test_FromJSONExceptionFlatDisplay(self):
     with self.assertRaises(ValueError):
         Verb.from_json('{"id": "test", "display": "flatdisplay"}')
예제 #39
0
 def test_FromJSON(self):
     verb = Verb.from_json('{"id": "test", "display": {"en-US": "test"}}')
     self.assertEqual(verb.id, 'test')
     self.displayVerificationHelper(verb.display)
예제 #40
0
 def test_InitVerb(self):
     substatement = SubStatement(verb=Verb(id='test'))
     self.verbVerificationHelper(substatement.verb)