Beispiel #1
0
class UniqueAnswerMCQExerciseQuestion(
        UniqueAnswerMCQExerciseQuestionJsonSerializer, ExerciseQuestion):
    """Multiple choice question with one possible answer only."""

    ## Object Id
    _id = db.ObjectIdField(default=ObjectId)

    ## Propositions
    propositions = db.ListField(
        db.EmbeddedDocumentField(UniqueAnswerMCQExerciseQuestionProposition))

    def without_correct_answer(self):
        son = super(UniqueAnswerMCQExerciseQuestion,
                    self).without_correct_answer()
        for proposition in son['propositions']:
            proposition.pop('is_correct_answer', None)
        return son

    def answer_with_data(self, data):
        return UniqueAnswerMCQExerciseQuestionAnswer.init_with_data(data)

    def get_proposition_by_id(self, propositionId):
        result = None
        for proposition in self.propositions:
            if proposition._id == propositionId:
                result = proposition
        return result
Beispiel #2
0
class DropdownExerciseQuestionAnswer(
        DropdownExerciseQuestionAnswerJsonSerializer, ExerciseQuestionAnswer):
    """Answers given for a dropdown question"""

    ## The list of chosen propositions, identified by their ObjectIds
    given_propositions = db.ListField(db.ObjectIdField())

    @classmethod
    def init_with_data(cls, data):
        obj = cls()
        obj.given_propositions = []
        import re
        for key in data:
            match = re.match(r"dropdown_(\w+)", key)
            if match:
                obj.given_propositions.append(ObjectId(data[key]))
        return obj

    def is_correct(self, question, parameters):
        propositions = question.get_propositions_by_id(self.given_propositions)
        all_question_propositions = []
        for dropdown in question.dropdowns:
            all_question_propositions.extend(dropdown.propositions)
        correct_propositions = filter(
            lambda proposition: proposition.is_correct_answer,
            all_question_propositions)
        return set(propositions) == set(correct_propositions)
Beispiel #3
0
class CategorizeExerciseQuestion(CategorizeExerciseQuestionJsonSerializer,
                                 ExerciseQuestion):
    """A list of items that need to be categorized."""

    ## Object Id
    _id = db.ObjectIdField(default=ObjectId)

    ## categories
    categories = db.ListField(
        db.EmbeddedDocumentField(CategorizeExerciseQuestionCategory))

    def without_correct_answer(self):
        son = super(CategorizeExerciseQuestion, self).without_correct_answer()
        all_items = []
        for category in son['categories']:
            all_items.extend(category.pop('items'))
        shuffle(all_items)
        son['items'] = all_items
        return son

    def answer_with_data(self, data):
        return CategorizeExerciseQuestionAnswer.init_with_data(data)

    def get_category_by_id(self, category_id):
        for category in self.categories:
            if category._id == category_id:
                return category

    def get_items_in_category_by_id(self, category_id, items_id):
        result = []
        category = self.get_category_by_id(category_id)
        for item in category.items:
            if item._id in items_id:
                result.append(item)
        return result
Beispiel #4
0
class DropdownExerciseQuestion(DropdownExerciseQuestionJsonSerializer,
                               ExerciseQuestion):
    """question where blanks need to be filled with word chosen from a dropdown list."""

    ## Object Id
    _id = db.ObjectIdField(default=ObjectId)

    ## the whole text, where blanks are tagged with [%N%] where N if Nth blank of the text
    text = db.StringField()

    ## Propositions
    dropdowns = db.ListField(
        db.EmbeddedDocumentField(DropdownExerciseQuestionDropdown))

    def without_correct_answer(self):
        son = super(DropdownExerciseQuestion, self).without_correct_answer()
        for dropdown in son['dropdowns']:
            for proposition in dropdown['propositions']:
                proposition.pop('is_correct_answer', None)
        return son

    def answer_with_data(self, data):
        return DropdownExerciseQuestionAnswer.init_with_data(data)

    def get_propositions_by_id(self, propositionsId):
        result = []
        for dropdown in self.dropdowns:
            for proposition in dropdown.propositions:
                if proposition._id in propositionsId:
                    result.append(proposition)
        return result
class RightOrWrongExerciseQuestion(RightOrWrongExerciseQuestionJsonSerializer,
                                   ExerciseQuestion):
    """Question with a right or wrong answer"""

    ## Object Id
    _id = db.ObjectIdField(default=ObjectId)

    ## Propositions
    propositions = db.ListField(
        db.EmbeddedDocumentField(RightOrWrongExerciseQuestionProposition))

    def without_correct_answer(self):
        son = super(RightOrWrongExerciseQuestion,
                    self).without_correct_answer()
        for proposition in son['propositions']:
            proposition.pop('is_correct_answer', None)
        return son

    def answer_with_data(self, data):
        return RightOrWrongExerciseQuestionAnswer.init_with_data(data)

    def get_proposition_by_id(self, propositionId):
        result = None
        for proposition in self.propositions:
            if proposition._id == propositionId:
                result = proposition
        return result
Beispiel #6
0
class MultipleAnswerMCQExerciseQuestion(MultipleAnswerMCQExerciseQuestionJsonSerializer, ExerciseQuestion):
    """Multiple choice question with several possible answers."""

    ## Object Id
    _id = db.ObjectIdField(default=ObjectId)

    ## Propositions
    propositions = db.ListField(db.EmbeddedDocumentField(MultipleAnswerMCQExerciseQuestionProposition))

    def without_correct_answer(self):
        son = super(MultipleAnswerMCQExerciseQuestion, self).without_correct_answer()
        for proposition in son['propositions']:
            proposition.pop('is_correct_answer', None)
        return son

    def answer_with_data(self, data):
        return MultipleAnswerMCQExerciseQuestionAnswer.init_with_data(data)

    def get_propositions_by_id(self, propositions_id):
        result = []
        for proposition in self.propositions:
            print(str(proposition._id))
            if proposition._id in propositions_id:
                result.append(proposition)
        return result
Beispiel #7
0
class OrderingExerciseQuestion(OrderingExerciseQuestionOrderingExerciseQuestionItemJsonSerializer, ExerciseQuestion):
    """A list of items that need to be ordered. May be horizontal or vertical"""

    ## Object Id
    _id = db.ObjectIdField(default=ObjectId)

    ## Propositions
    items = db.ListField(db.EmbeddedDocumentField(OrderingExerciseQuestionItem))

    def without_correct_answer(self):
        son = super(OrderingExerciseQuestion, self).without_correct_answer()
        shuffle(son['items'])
        return son

    def answer_with_data(self, data):
        return OrderingExerciseQuestionAnswer.init_with_data(data)

    def get_items_by_id(self, itemsId):
        result = []
        for itemId in itemsId:
            print(itemId)
            result.append(self.get_item_by_id(itemId))
        return result

    def get_item_by_id(self, itemId):
        for item in self.items:
            if str(item._id) == itemId:
                return item
        return None
Beispiel #8
0
class DropdownExerciseQuestionDropdown(
        DropdownExerciseQuestionDropdownJsonSerializer, db.EmbeddedDocument):
    """Stores a list of propositions to a blank field in a text."""

    ## Object Id
    _id = db.ObjectIdField(default=ObjectId)

    ## Text
    propositions = db.ListField(
        db.EmbeddedDocumentField(DropdownExerciseQuestionProposition))
Beispiel #9
0
class CategorizeExerciseQuestionCategory(
        CategorizeExerciseQuestionCategoryJsonSerializer, db.EmbeddedDocument):
    """Stores a category for the categorize question."""

    ## Object Id
    _id = db.ObjectIdField(default=ObjectId)

    ## Text
    title = db.StringField()

    ## items that belong to this category
    items = db.ListField(
        db.EmbeddedDocumentField(CategorizeExerciseQuestionItem))
Beispiel #10
0
class CategorizeExerciseQuestionAnswer(
        CategorizeExerciseQuestionAnswerJsonSerializer,
        ExerciseQuestionAnswer):
    """categorized items given for this Categorize question."""

    ## The categories sent by the client, identified by their ObjectIds.
    given_categories = db.ListField(db.ObjectIdField())

    ## The categorized items, identified by their ObjectIds, in the requested categories.
    ## The first level order is the same as the given_categories
    given_categorized_items = db.ListField(db.ListField(db.ObjectIdField()))

    @classmethod
    def init_with_data(cls, data):
        obj = cls()
        obj.given_categories = []
        obj.given_categorized_items = []
        for category, items in data['categorized_items'].iteritems():
            obj.given_categories.append(ObjectId(category))
            categorized_items = []
            for given_item in items:
                categorized_items.append(ObjectId(given_item))
            obj.given_categorized_items.append(categorized_items)
        return obj

    def is_correct(self, question, parameters):
        answer_categories_items = self.given_categorized_items
        result = True
        for i in range(0, len(answer_categories_items)):
            category_items = question.get_items_in_category_by_id(
                self.given_categories[i], self.given_categorized_items[i])
            correct_category = question.get_category_by_id(
                self.given_categories[i])
            if set(category_items) != set(correct_category.items):
                result = False
                break
        return result
Beispiel #11
0
class OrderingExerciseQuestionAnswer(OrderingExerciseQuestionAnswerJsonSerializer, ExerciseQuestionAnswer):
    """Ordered items given for this ordering question."""

    ## The given propositions, identified by their ObjectIds
    given_ordered_items = db.ListField(db.ObjectIdField())

    @classmethod
    def init_with_data(cls, data):
        obj = cls()
        obj.given_ordered_items = data['ordered_items']
        return obj

    def is_correct(self, question, parameters):
        ordered_items = question.get_items_by_id(self.given_ordered_items)
        correct_ordered_items = question.items
        return ordered_items == correct_ordered_items
Beispiel #12
0
class MultipleAnswerMCQExerciseQuestionAnswer(MultipleAnswerMCQExerciseQuestionAnswerJsonSerializer, ExerciseQuestionAnswer):
    """Answers given to a multiple-answer MCQ."""

    ## The list of chosen propositions, identified by their ObjectIds
    given_propositions = db.ListField(db.ObjectIdField())

    @classmethod
    def init_with_data(cls, data):
        obj = cls()
        obj.given_propositions = []
        for proposition in data['propositions']:
            obj.given_propositions.append(ObjectId(proposition))
        return obj

    def is_correct(self, question, parameters):
        propositions = question.get_propositions_by_id(self.given_propositions)
        correct_propositions = filter(lambda proposition: proposition.is_correct_answer, question.propositions)
        return set(propositions) == set(correct_propositions)
class SkillValidationAttempt(SkillValidationAttemptJsonSerializer, Activity):
    """
    Records any attempt at an exercise.
    """

    ### PROPERTIES

    ## Skill
    skill = db.ReferenceField('Skill')

    @property
    def object(self):
        return self.skill

    ## Question answers
    question_answers = db.ListField(
        db.EmbeddedDocumentField(ExerciseAttemptQuestionAnswer))

    is_validated = db.BooleanField(default=False)
    """ Is exercise validated """

    end_date = db.DateTimeField()
    """ The date when the attempt is ended """

    @property
    def max_mistakes(self):
        if self.skill and not isinstance(self.skill, DBRef):
            return self.skill.validation_exercise.max_mistakes
        return None

    @property
    def nb_right_answers(self):
        return len(
            filter(lambda qa: qa.is_answered_correctly, self.question_answers))

    @property
    def nb_questions(self):
        return len(self.question_answers)

    @property
    def duration(self):
        if not self.end_date:
            return None
        else:
            return self.end_date - self.date

    ### METHODS

    @classmethod
    def init_with_skill(cls, skill):
        """Initiate an validation attempt for a given skill."""
        obj = cls()
        obj.skill = skill

        questions = skill.random_questions()
        obj.question_answers = map(
            lambda q: ExerciseAttemptQuestionAnswer.init_with_question(q),
            questions)

        return obj

    def clean(self):
        super(SkillValidationAttempt, self).clean()
        self.type = "exercise_attempt"

    def __unicode__(self):
        if self.skill is not None:
            return self.skill.title
        return self.id

    def question_answer(self, question_id):
        oid = ObjectId(question_id)
        for question_answer in self.question_answers:
            if question_answer.question_id == oid:
                return question_answer
        raise KeyError("Question not found.")

    def set_question_answer(self, question_id, question_answer):
        oid = ObjectId(question_id)
        for (index, qa) in enumerate(self.question_answers):
            if qa.question_id == oid:
                self.question_answers[index] = question_answer
                return question_answer
        raise KeyError("Question not found.")

    def save_answer(self, question_id, data):
        """
        Saves an answer (ExerciseQuestionAnswer) to a question (referenced by its ObjectId).
        """

        question = self.skill.question(question_id)
        attempt_question_answer = self.question_answer(question_id)
        question_answer = question.answer_with_data(data)
        attempt_question_answer.given_answer = question_answer
        attempt_question_answer.is_answered_correctly = question_answer.is_correct(
            question, attempt_question_answer.parameters)
        self.set_question_answer(question_id, attempt_question_answer)

    def start_question(self, question_id):
        """
        Records the datetime at which the given question has been started
        :param question_id: the id of the question which has just been started
        """
        attempt_question_answer = self.question_answer(question_id)
        attempt_question_answer.asked_date = datetime.datetime.now

    def end(self):
        """
        Records the "now" date as the date when the user has finished the attempt
        """
        self.end_date = datetime.datetime.now

    def is_skill_validation_validated(self):
        nb_total_questions = len(self.question_answers)
        answered_questions = filter(lambda a: a.given_answer is not None,
                                    self.question_answers)
        return len(answered_questions) >= nb_total_questions

    def is_attempt_completed(self):
        nb_total_questions = len(self.question_answers)
        nb_max_mistakes = self.skill.validation_exercise.max_mistakes
        answered_questions = filter(lambda a: a.given_answer is not None,
                                    self.question_answers)
        if len(answered_questions) >= nb_total_questions:
            right_answers = filter(lambda a: a.is_answered_correctly,
                                   answered_questions)
            if len(right_answers) >= nb_total_questions - nb_max_mistakes:
                return True

        return False
Beispiel #14
0
class User(UserJsonSerializer, CsvSerializer, SyncableDocument):

    full_name = db.StringField(unique=False, required=True)

    email = db.EmailField(unique=False)

    country = db.StringField()

    occupation = db.StringField()

    organization = db.StringField()

    active = db.BooleanField(default=True)

    accept_cgu = db.BooleanField(required=True, default=False)

    roles = db.ListField(db.ReferenceField(Role))

    @property
    def inscription_time(self):
        from MookAPI.services import misc_activities
        creation_activity = misc_activities.first(user=self,
                                                  type="register_user_attempt",
                                                  object_title="success")
        return creation_activity.date if creation_activity else "#NO INSCRIPTION DATE FOUND#"

    @property
    def inscription_date(self):
        inscription_date = self.inscription_time
        if isinstance(inscription_date, datetime):
            inscription_date = inscription_date.strftime("%Y-%m-%d")
        return inscription_date

    @property
    def tracks(self):
        from MookAPI.services import completed_tracks
        completedTracks = completed_tracks.__model__.objects(
            user=self).only('track').distinct('track')
        return "|".join(track.title for track in completedTracks)

    @property
    def skills(self):
        from MookAPI.services import completed_skills
        completedSkills = completed_skills.__model__.objects(
            user=self).only('skill').distinct('skill')
        return "|".join(skill.title for skill in completedSkills)

    def courses_info(self, analytics=False):
        info = dict(tracks=dict(), skills=dict(), resources=dict())

        from MookAPI.services import tracks
        for track in tracks.all():
            info['tracks'][str(track.id)] = track.user_info(
                user=self, analytics=analytics)
            for skill in track.skills:
                info['skills'][str(skill.id)] = skill.user_info(
                    user=self, analytics=analytics)
                for lesson in skill.lessons:
                    for resource in lesson.resources:
                        info['resources'][str(
                            resource.id)] = resource.user_info(
                                user=self, analytics=analytics)

        return info

    @property
    def tutors(self):
        from MookAPI.services import tutoring_relations
        relations = tutoring_relations.find(student=self, accepted=True)
        return [relation.tutor for relation in relations]

    @property
    def students(self):
        from MookAPI.services import tutoring_relations
        relations = tutoring_relations.find(tutor=self, accepted=True)
        return [relation.student for relation in relations]

    ## Awaiting: the current user was requested
    @property
    def awaiting_tutor_requests(self):
        from MookAPI.services import tutoring_relations
        relations = tutoring_relations.find(tutor=self,
                                            initiated_by='student',
                                            accepted=False)
        return [relation.student for relation in relations]

    @property
    def awaiting_student_requests(self):
        from MookAPI.services import tutoring_relations
        relations = tutoring_relations.find(student=self,
                                            initiated_by='tutor',
                                            accepted=False)
        return [relation.tutor for relation in relations]

    ## Not acknowledged: Requests initiated by the current user have been accepted
    @property
    def not_acknowledged_tutors(self):
        from MookAPI.services import tutoring_relations
        relations = tutoring_relations.find(student=self,
                                            initiated_by='student',
                                            accepted=True,
                                            acknowledged=False)
        return [relation.tutor for relation in relations]

    @property
    def not_acknowledged_students(self):
        from MookAPI.services import tutoring_relations
        relations = tutoring_relations.find(tutor=self,
                                            initiated_by='tutor',
                                            accepted=True,
                                            acknowledged=False)
        return [relation.student for relation in relations]

    ## Pending: the current user made the request
    @property
    def pending_tutors(self):
        from MookAPI.services import tutoring_relations
        relations = tutoring_relations.find(student=self,
                                            initiated_by='student',
                                            accepted=False)
        return [relation.tutor for relation in relations]

    @property
    def pending_students(self):
        from MookAPI.services import tutoring_relations
        relations = tutoring_relations.find(tutor=self,
                                            initiated_by='tutor',
                                            accepted=False)
        return [relation.student for relation in relations]

    phagocyted_by = db.ReferenceField('self', required=False)

    def is_track_test_available_and_never_attempted(self, track):
        # FIXME Make more efficient search using Service
        from MookAPI.services import unlocked_track_tests
        if unlocked_track_tests.find(user=self, track=track).count() > 0:
            from MookAPI.services import track_validation_attempts
            attempts = track_validation_attempts.find(user=self)
            return all(attempt.track != track for attempt in attempts)

        return False

    def update_progress(self, self_credentials):
        from MookAPI.services import \
            completed_resources, \
            unlocked_track_tests
        skills = set()
        tracks = set()
        for activity in completed_resources.find(user=self):
            skills.add(activity.resource.skill)
        for skill in skills:
            tracks.add(skill.track)
        for track in tracks:
            track_progress = track.user_progress(self)
            if unlocked_track_tests.find(user=self, track=track).count(
            ) == 0 and track_progress['current'] >= track_progress['max']:
                self_credentials.unlock_track_validation_test(track)

    @property
    def url(self, _external=False):
        return url_for("users.get_user_info",
                       user_id=self.id,
                       _external=_external)

    @property
    def username(self):
        credentials = self.all_credentials
        if not credentials:
            return "#NO USERNAME FOUND#"
        return credentials[0].username

    @property
    def all_credentials(self):
        from MookAPI.services import user_credentials
        return user_credentials.find(user=self)

    def credentials(self, local_server=None):
        from MookAPI.services import user_credentials
        return user_credentials.find(user=self, local_server=local_server)

    def all_synced_documents(self, local_server=None):
        items = super(User, self).all_synced_documents()

        from MookAPI.services import activities, tutoring_relations
        for creds in self.credentials(local_server=local_server):
            items.extend(creds.all_synced_documents(local_server=local_server))
        for activity in activities.find(user=self):
            items.extend(
                activity.all_synced_documents(local_server=local_server))
        for student_relation in tutoring_relations.find(tutor=self):
            items.extend(
                student_relation.all_synced_documents(
                    local_server=local_server))
        for tutor_relation in tutoring_relations.find(student=self):
            items.extend(
                tutor_relation.all_synced_documents(local_server=local_server))

        return items

    def __unicode__(self):
        return self.full_name or self.email or self.id

    def phagocyte(self, other, self_credentials):
        if other == self:
            self.update_progress(self_credentials)
            self.save()
            return self

        from MookAPI.services import \
            activities, \
            tutoring_relations, \
            user_credentials
        for creds in user_credentials.find(user=other):
            creds.user = self
            creds.save(validate=False)
        for activity in activities.find(user=other):
            activity.user = self
            activity.save()
        for student_relation in tutoring_relations.find(tutor=other):
            student_relation.tutor = self
            student_relation.save()
        for tutor_relation in tutoring_relations.find(student=other):
            tutor_relation.student = self
            tutor_relation.save()

        other.active = False
        other.phagocyted_by = self
        other.save()

        self.update_progress(self_credentials)
        self.save()

        return self

    @classmethod
    def field_names_header_for_csv(cls):
        return [
            'Full name', 'Username', 'Email', 'Country', 'Occupation',
            'Organization', 'Inscription date', 'Tracks', 'Skills'
        ]

    def get_field_names_for_csv(cls):
        return 'full_name username email country occupation organization inscription_date tracks skills'.split(
        )
Beispiel #15
0
class SyncTask(db.Document):
    """A document that describes a sync operation to perform on the local server."""

    ### PROPERTIES

    queue_position = db.SequenceField()
    """An auto-incrementing counter determining the order of the operations to perform."""

    type = db.StringField(choices=('update', 'delete'))
    """The operation to perform (``update`` or ``delete``)."""

    central_id = db.ObjectIdField()
    """The ``id`` of the ``SyncableDocument`` on the central server."""

    class_name = db.StringField()
    """The class of the ``SyncableDocument`` affected by this operation."""

    url = db.StringField()
    """The URL at which the information of the document can be downloaded. Null if ``type`` is ``delete``."""

    errors = db.ListField(db.StringField())
    """The list of the errors that occurred while trying to perform the operation."""
    def __unicode__(self):
        return "%s %s document with central id %s" % (
            self.type, self.class_name, self.central_id)

    _service = None

    @property
    def service(self):
        if not self._service:
            from MookAPI.helpers import get_service_for_class
            self._service = get_service_for_class(self.class_name)
        return self._service

    @property
    def model(self):
        return self.service.__model__

    def _fetch_update(self, connector, local_document):
        r = connector.get(self.url)

        if r.status_code == 200:
            son = json_util.loads(r.text)
            document = self.model.from_json(
                son['data'],
                from_central=True,
                overwrite_document=local_document,
                upload_path=connector.local_files_path)
            document.clean()
            document.save(
                validate=False
            )  # FIXME MongoEngine bug, hopefully fixed in next version
            return document

        else:
            raise Exception("Could not fetch info, got status code %d" %
                            r.status_code)

    def _update_local_server(self, connector, local_document):
        tracks_before = set(local_document.synced_tracks)
        users_before = set(local_document.synced_users)

        document = self._fetch_update(connector, local_document)

        if document:
            from . import sync_tasks_service

            tracks_after = set(document.synced_tracks)
            users_after = set(document.synced_users)

            for new_track in tracks_after - tracks_before:
                sync_tasks_service.fetch_tasks_whole_track(
                    new_track.id, connector)
            for new_user in users_after - users_before:
                sync_tasks_service.fetch_tasks_whole_user(
                    new_user.id, connector)
            for obsolete_track in tracks_before - tracks_after:
                sync_tasks_service.create_delete_task_existing_document(
                    obsolete_track)
            for obsolete_user in users_before - users_after:
                sync_tasks_service.create_delete_task_existing_document(
                    obsolete_user)

        return document

    def _depile_update(self, connector):
        try:
            local_document = self.service.get(central_id=self.central_id)
        except Exception as e:  # TODO Distinguish between not found and found >1 results
            local_document = None

        if local_document:
            from MookAPI.services import local_servers
            if local_servers._isinstance(local_document):
                return self._update_local_server(connector, local_document)

        return self._fetch_update(connector, local_document)

    def _depile_delete(self):
        try:
            local_document = self.service.get(central_id=self.central_id)
        except Exception as e:
            pass  # FIXME What should we do in that case?
        else:
            for document in reversed(local_document.all_synced_documents()):
                document.delete()

        return True

    def depile(self, connector=None):

        rv = False

        try:
            if self.type == 'update':
                rv = self._depile_update(connector=connector)
            elif self.type == 'delete':
                rv = self._depile_delete()
            else:
                self.errors.append("Unrecognized task type")
                self.save()
                return False
        except Exception as e:
            self.errors.append(str(e.message) or str(e.strerror))
            self.save()
            rv = False
        else:
            self.delete()

        return rv
Beispiel #16
0
class Resource(ResourceJsonSerializer, SyncableDocument):
    """
    .. _Resource:
    
    Any elementary pedagogical resource.
    Contains the metadata and a ResourceContent_ embedded document.
    Resource_ objects are organized by Lesson_ objects, *i.e.* each Resource_ references a parent Lesson_.
    """

    meta = {'allow_inheritance': True}

    ### PROPERTIES

    is_published = db.BooleanField(default=True)
    """Whether the resource should appear on the platform"""

    is_additional = db.BooleanField(default=False)
    """True if the resource is an additional resource, i.e. has a Resource parent (instead of a Lesson)"""

    title = db.StringField(required=True)
    """The title of the Resource_."""

    slug = db.StringField(unique=True)
    """A human-readable unique identifier for the Resource_."""

    ## Will be implemented later
    # creator = db.ReferenceField('User')
    # """The user who created the resource."""

    description = db.StringField()
    """A text describing the Resource_."""

    order = db.IntField()
    """The order of the Resource_ in the Lesson_."""

    keywords = db.ListField(db.StringField())
    """A list of keywords to index the Resource_."""

    date = db.DateTimeField(default=datetime.datetime.now, required=True)
    """The date the Resource_ was created."""

    parent = db.ReferenceField('Lesson')
    """The parent hierarchy object (usually Lesson, but can be overridden)."""

    parent_resource = db.ReferenceField('Resource')
    """The parent hierarchy object (usually Lesson, but can be overridden)."""

    resource_content = db.EmbeddedDocumentField(ResourceContent)
    """The actual content of the Resource_, stored in a ResourceContent_ embedded document."""

    ### VIRTUAL PROPERTIES

    @property
    def url(self, _external=False):
        return url_for("resources.get_resource",
                       resource_id=self.id,
                       _external=_external)

    def is_validated_by_user(self, user):
        """Whether the current user (if any) has validated this Resource_."""
        from MookAPI.services import completed_resources

        return completed_resources.find(resource=self, user=user).count() > 0

    @property
    def is_validated(self):
        try:
            verify_jwt()
        except:
            pass
        if not current_user:
            return None
        return self.is_validated_by_user(current_user.user)

    @property
    def skill(self):
        """Shorthand virtual property to the parent Skill_ of the parent Lesson_."""
        if self.parent_resource:
            return self.parent_resource.skill if not isinstance(
                self.parent_resource, DBRef) else None
        return self.parent.skill if not isinstance(self.parent,
                                                   DBRef) else None

    @property
    def track(self):
        """Shorthand virtual property to the parent Track_ of the parent Skill_ of the parent Lesson_."""
        if self.skill and not isinstance(self.skill, DBRef):
            return self.skill.track
        return None

    @property
    def additional_resources(self):
        """A queryset of the Resources_ objects that are additional resources to the current Resource_."""
        from MookAPI.services import resources

        return resources.find(parent_resource=self).order_by('order', 'title')

    @property
    def additional_resources_refs(self):
        return [
            additional_resource.to_json_dbref()
            for additional_resource in self.additional_resources
        ]

    ### METHODS

    def siblings(self):
        """A queryset of Resource_ objects in the same Lesson_, including the current Resource_."""
        return Resource.objects.order_by('order',
                                         'title').filter(parent=self.parent)

    def siblings_strict(self):
        """A queryset of Resource_ objects in the same Lesson_, excluding the current Resource_."""
        return Resource.objects.order_by('order',
                                         'title').filter(parent=self.parent,
                                                         id__ne=self.id)

    def aunts(self):
        """A queryset of Lesson_ objects in the same Skill_, including the current Lesson_."""
        return self.parent.siblings()

    def aunts_strict(self):
        """A queryset of Lesson_ objects in the same Skill_, excluding the current Lesson_."""
        return self.parent.siblings_strict()

    def cousins(self):
        """A queryset of Resource_ objects in the same Skill_, including the current Resource_."""
        return Resource.objects.order_by(
            'parent', 'order', 'title').filter(parent__in=self.aunts())

    def cousins_strict(self):
        """A queryset of Resource_ objects in the same Skill_, excluding the current Resource_."""
        return Resource.objects.order_by(
            'parent', 'order', 'title').filter(parent__in=self.aunts_strict())

    def _set_slug(self):
        """Sets a slug for the hierarchy level based on the title."""

        slug = self.slug or slugify(self.title)

        def alternate_slug(text, k=1):
            return text if k <= 1 else "{text}-{k}".format(text=text, k=k)

        k = 0
        kmax = 10**4
        while k < kmax:
            if self.id is None:
                req = self.__class__.objects(slug=alternate_slug(slug, k))
            else:
                req = self.__class__.objects(slug=alternate_slug(slug, k),
                                             id__ne=self.id)
            if len(req) > 0:
                k = k + 1
                continue
            else:
                break
        self.slug = alternate_slug(slug, k) if k <= kmax else None

    def clean(self):
        super(Resource, self).clean()
        self._set_slug()

    @property
    def bg_color(self):
        return self.track.bg_color

    def user_analytics(self, user):
        from MookAPI.services import visited_resources
        return dict(
            nb_visits=visited_resources.find(user=user, resource=self).count())

    def user_info(self, user, analytics=False):
        info = dict(is_validated=self.is_validated_by_user(user))
        if analytics:
            info['analytics'] = self.user_analytics(user)
        return info

    @property
    def hierarchy(self):
        """
        Returns an array of the breadcrumbs up until the current object: [Track_, Skill_, Lesson_, Resource_]
        """
        rv = []

        if self.is_additional:
            rv.extend([
                self.parent_resource.track.to_json_dbref(),
                self.parent_resource.skill.to_json_dbref(),
                self.parent_resource.parent.to_json_dbref(),
                self.parent_resource.to_json_dbref(),
                self.to_json_dbref()
            ])
        else:
            rv.extend([
                self.track.to_json_dbref(),
                self.skill.to_json_dbref(),
                self.parent.to_json_dbref(),
                self.to_json_dbref()
            ])

        return rv

    def __unicode__(self):
        return "%s [%s]" % (self.title, self.__class__.__name__)

    def top_level_syncable_document(self):
        return self.track

    def all_synced_documents(self, local_server=None):
        items = super(Resource,
                      self).all_synced_documents(local_server=local_server)

        for additional_resource in self.additional_resources:
            items.extend(
                additional_resource.all_synced_documents(
                    local_server=local_server))

        return items
Beispiel #17
0
class LocalServer(LocalServerJsonSerializer, SyncableDocument):
    """
    .. _LocalServer:

    This collection contains the list of all central servers connected to the current central server.
    """

    ### PROPERTIES

    name = db.StringField()

    key = db.StringField(unique=True)

    secret = db.StringField()

    synced_tracks = db.ListField(
        db.ReferenceField('Track', reverse_delete_rule=PULL))

    @property
    def synced_users(self):
        from MookAPI.services import user_credentials
        return [
            creds.user for creds in user_credentials.find(local_server=self)
        ]

    @property
    def synced_documents(self):
        from MookAPI.services import static_pages
        documents = []
        documents.extend(self.synced_tracks)
        documents.extend(self.synced_users)
        documents.extend(static_pages.all())
        return documents

    last_sync = db.DateTimeField()

    @property
    def url(self, _external=False):
        return url_for("local_servers.get_local_server",
                       local_server_id=self.id,
                       _external=_external)

    def syncs_document(self, document):
        top_level_document = document.top_level_syncable_document()
        return top_level_document in self.synced_documents

    def get_sync_list(self):
        updates = []
        deletes = []

        updates.extend(self.items_to_update(local_server=self))

        for document in self.synced_documents:
            updates.extend(document.items_to_update(local_server=self))
            deletes.extend(document.items_to_delete(local_server=self))

        return dict(
            updates=unique(updates),
            deletes=
            deletes  # 'deletes' contains (unhashable) DBRef objects, can't apply 'unique' to it
        )

    def reset(self):
        self.last_sync = None

    def __unicode__(self):
        return "%s [%s]" % (self.name, self.key)

    @staticmethod
    def hash_secret(secret):
        """
        Return the md5 hash of the secret+salt
        """
        return bcrypt.encrypt(secret)

    def verify_secret(self, secret):
        return bcrypt.verify(secret, self.secret)
Beispiel #18
0
class ExerciseResourceContent(ExerciseResourceContentJsonSerializer,
                              ResourceContent):
    unique_answer_mcq_questions = db.ListField(
        db.EmbeddedDocumentField(UniqueAnswerMCQExerciseQuestion))
    """A (possibly empty) list of unique-answer multiple-choice questions (`UniqueAnswerMCQExerciseQuestion`)."""

    multiple_answer_mcq_questions = db.ListField(
        db.EmbeddedDocumentField(MultipleAnswerMCQExerciseQuestion))
    """A (possibly empty) list of multiple-answer multiple-choice questions (`MultipleAnswerMCQExerciseQuestion`)."""

    right_or_wrong_questions = db.ListField(
        db.EmbeddedDocumentField(RightOrWrongExerciseQuestion))
    """A (possibly empty) list of multiple-answer multiple-choice questions (`RightOrWrongExerciseQuestion`)."""

    dropdown_questions = db.ListField(
        db.EmbeddedDocumentField(DropdownExerciseQuestion))
    """A (possibly empty) list of dropdown questions (`DropdownExerciseQuestion`)."""

    ordering_questions = db.ListField(
        db.EmbeddedDocumentField(OrderingExerciseQuestion))
    """A (possibly empty) list of ordering questions (`OrderingExerciseQuestion`)."""

    categorize_questions = db.ListField(
        db.EmbeddedDocumentField(CategorizeExerciseQuestion))
    """A (possibly empty) list of categorizing questions (`CategorizeExerciseQuestion`)."""
    @property
    def questions(self):
        """A list of all questions, whatever their type."""

        questions = []
        questions.extend(self.unique_answer_mcq_questions)
        questions.extend(self.multiple_answer_mcq_questions)
        questions.extend(self.right_or_wrong_questions)
        questions.extend(self.dropdown_questions)
        questions.extend(self.ordering_questions)
        questions.extend(self.categorize_questions)

        return questions

    def question(self, question_id):
        """A getter for a question with a known `_id`."""

        oid = bson.ObjectId(question_id)
        for question in self.questions:
            if question._id == oid:
                return question

        raise exceptions.KeyError("Question not found.")

    def random_questions(self, number=None):
        """
        A list of random questions.
        If `number` is not specified, it will be set to the exercise's `number_of_questions` property.
        The list will contain `number` questions, or all questions if there are not enough questions in the exercise.
        """

        if not number:
            number = self.number_of_questions or len(self.questions)

        all_questions = self.questions
        random.shuffle(all_questions)
        return all_questions[:number]

    number_of_questions = db.IntField()
    """The number of questions to ask from this exercise."""

    max_mistakes = db.IntField()
    """The number of mistakes authorized before failing the exercise."""

    fail_linked_resource = db.ReferenceField(Resource)
    """A resource to look again when failing the exercise."""

    def clean(self):
        super(ExerciseResourceContent, self).clean()
        # FIXME This should be done in validate and raise an error. Do that when MongoEngine is fixed.
        if self.fail_linked_resource:
            if self.fail_linked_resource.track != self._instance.track:
                self.fail_linked_resource = None