class TutoringRelation(TutoringRelationJsonSerializer, SyncableDocument): tutor = db.ReferenceField('User') student = db.ReferenceField('User') accepted = db.BooleanField(default=False) acknowledged = db.BooleanField(default=False) # has the accepted notification been seen by the initiator INITIATORS = ('tutor, student') initiated_by = db.StringField(choices=INITIATORS) @property def url(self, _external=False): return url_for("tutoring.get_relation", relation_id=self.id, _external=_external)
class StartedTrack(StartedTrackJsonSerializer, Activity): """ Records when a resource is completed by a user """ track = db.ReferenceField('Track') @property def object(self): return self.track def clean(self): super(StartedTrack, self).clean() self.type = "started_track"
class UnlockedTrackTest(UnlockedTrackTestJsonSerializer, Activity): """ Records when a resource is completed by a user """ track = db.ReferenceField('Track') @property def object(self): return self.track def clean(self): super(UnlockedTrackTest, self).clean() self.type = "unlocked_track_test"
class VisitedTrack(VisitedTrackJsonSerializer, Activity): """ Records when a track is visited by a user """ track = db.ReferenceField('Track') @property def object(self): return self.track def clean(self): super(VisitedTrack, self).clean() self.type = "visited_track"
class VisitedResource(VisitedResourceJsonSerializer, Activity): """ Records when a resource is visited by a user """ resource = db.ReferenceField('Resource') @property def object(self): return self.resource def clean(self): super(VisitedResource, self).clean() self.type = "visited_resource"
class VisitedSkill(VisitedSkillJsonSerializer, Activity): """ Records when a skill is visited by a user """ skill = db.ReferenceField('Skill') @property def object(self): return self.skill def clean(self): super(VisitedSkill, self).clean() self.type = "visited_skill"
class TrackValidationResource(TrackValidationResourceJsonSerializer, ExerciseResource): """An track validation test with a list of questions.""" parent = db.ReferenceField('Track') """The parent Hierarchy object (here, it is a Track).""" @property def track(self): return self.parent @property def hierarchy(self): """ Returns an array of the breadcrumbs up until the current object: [Track_, Skill_, Lesson_, Resource_] """ return [self.track.to_json_dbref(), self.to_json_dbref()]
class Activity(ActivityJsonSerializer, CsvSerializer, SyncableDocument): """Describes any kind of user activity.""" meta = {'allow_inheritance': True, 'indexes': ['+date', 'user', 'type']} ### PROPERTIES credentials = db.ReferenceField('UserCredentials') """The credentials under which the user was logged when they performed the action.""" user = db.ReferenceField('User') """The user performing the activity.""" user_username = db.StringField(default="") """The username (= unique id) of the user who has performed the activity""" user_name = db.StringField(default="") """The full name of the user who has performed the activity""" # FIXME this has to be set using the credentials provided date = db.DateTimeField(default=datetime.datetime.now, required=True) """The date at which the activity was performed.""" local_server = db.ReferenceField('LocalServer') """The local server on which the activity has been performed""" local_server_name = db.StringField() """The name of the local server on which the activity has been performed""" type = db.StringField() """ The type of the activity, so we can group the activities by type to better analyse them. This is supposed to be defaulted/initialized in each subclass""" @property def object(self): return None object_title = db.StringField() """ The title of the object associated to this activity. It allows a better comprehension of the activity than the activity_id. This is supposed to be defaulted/initialized in each subclass """ @property def url(self, _external=False): print("Activity (%s) url: %s" % (self._cls, self.id)) return url_for("activity.get_activity", activity_id=self.id, _external=_external) @property def local_server_id(self): return self.local_server.id if self.local_server is not None else "" @property def user_id(self): return self.user.id if self.user is not None else "" def clean(self): super(Activity, self).clean() if self.object and not isinstance(self.object, DBRef): self.object_title = getattr(self.object, 'title', None) if self.credentials and not isinstance(self.credentials, DBRef): self.user = self.credentials.user self.user_username = self.credentials.username self.local_server = self.credentials.local_server if self.user and not isinstance(self.user, DBRef): self.user_name = self.user.full_name if self.local_server and not isinstance(self.local_server, DBRef): self.local_server_name = self.local_server.name @classmethod def field_names_header_for_csv(cls): return [ 'Koombook id', 'Koombook name', 'User id', 'User username', 'User full name', 'Date - Time', 'Action type', 'Object id', 'Object title', 'Object-specific data' ] def top_level_syncable_document(self): return self.user def all_synced_documents(self, local_server=None): if self.object and not isinstance(self.object, DBRef): if not local_server.syncs_document(self.object): return [] return super(Activity, self).all_synced_documents(local_server=local_server) def __unicode__(self): return "Activity with type %s for user %s" % (self.type, self.user) def get_field_names_for_csv(self): """ this method gives the fields to export as csv row, in a chosen order """ return [ 'local_server_id', 'local_server_name', 'user_id', 'user_username', 'user_name', 'date', 'type', 'object', 'object_title' ]
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)
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
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
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
class Skill(SkillJsonSerializer, ResourceHierarchy): """ .. _Skill: Second level of Resource_ hierarchy. Their ascendants are Track_ objects. Their descendants are Lesson_ objects. """ ### PROPERTIES ## Parent track track = db.ReferenceField('Track') """The parent Track_.""" ## icon image icon = db.ImageField() """An icon to illustrate the Skill_.""" ## short description short_description = db.StringField() """The short description of the skill, to appear where there is not enough space for the long one.""" ## skill validation test validation_exercise = db.EmbeddedDocumentField(SkillValidationExercise) """The exercise that the user might take to validate the skill.""" ### VIRTUAL PROPERTIES @property def icon_url(self, _external=True): """The URL where the skill icon can be downloaded.""" return url_for("hierarchy.get_skill_icon", skill_id=self.id, _external=_external) @property def url(self, _external=False): return url_for("hierarchy.get_skill", skill_id=self.id, _external=_external) @property def lessons(self): """A queryset of the Lesson_ objects that belong to the current Skill_.""" from MookAPI.services import lessons return lessons.find(skill=self).order_by('order', 'title') @property def lessons_refs(self): return [lesson.to_json_dbref() for lesson in self.lessons] def is_validated_by_user(self, user): """Whether the current_user validated the hierarchy level based on their activity.""" from MookAPI.services import completed_skills return completed_skills.find( skill=self, user=user, is_validated_through_test=True).count() > 0 def user_progress(self, user): current = 0 nb_resources = 0 for lesson in self.lessons: for resource in lesson.resources: nb_resources += 1 if resource.is_validated_by_user(user): current += 1 return {'current': current, 'max': nb_resources} @property def bg_color(self): return self.track.bg_color @property def hierarchy(self): return [self.track.to_json_dbref(), self.to_json_dbref()] ### METHODS def _add_instance(self, obj): """This is a hack to provide the ``_instance`` property to the shorthand question-getters.""" def _add_instance_single_object(obj): obj._instance = self return obj if isinstance(obj, list): return map(_add_instance_single_object, obj) else: return _add_instance_single_object(obj) def user_analytics(self, user): analytics = super(Skill, self).user_analytics(user) from MookAPI.services import skill_validation_attempts, visited_skills skill_validation_attempts = skill_validation_attempts.find( user=user).order_by('-date') analytics['last_attempts_scores'] = map( lambda a: { "date": a.date, "nb_questions": a.nb_questions, "score": a.nb_right_answers }, skill_validation_attempts[:5]) nb_finished_attempts = 0 total_duration = datetime.timedelta(0) for attempt in skill_validation_attempts: if attempt.duration: nb_finished_attempts += 1 total_duration += attempt.duration if nb_finished_attempts > 0: analytics['average_time_on_exercise'] = math.floor( (total_duration / nb_finished_attempts).total_seconds()) else: analytics['average_time_on_exercise'] = 0 analytics['nb_attempts'] = skill_validation_attempts.count() analytics['nb_visits'] = visited_skills.find(user=user, skill=self).count() return analytics def top_level_syncable_document(self): return self.track def all_synced_documents(self, local_server=None): items = super(Skill, self).all_synced_documents(local_server=local_server) for lesson in self.lessons: items.extend( lesson.all_synced_documents(local_server=local_server)) return items @property def questions(self): """A list of all children exercises' questions, whatever their type.""" from MookAPI.services import exercise_resources questions = [] for l in self.lessons: for r in l.resources: if exercise_resources._isinstance(r): questions.extend(r.questions) return questions def question(self, question_id): """A shorthand getter for a question with a known `_id`.""" from MookAPI.services import exercise_resources oid = bson.ObjectId(question_id) for l in self.lessons: for r in l.resources: if exercise_resources._isinstance(r): for q in r.questions: if q._id == oid: return r._add_instance(q) return None def random_questions(self, number=None): """ A shorthand getter for a list of random questions. See the documentation of `SkillValidationExercise.random_questions`. """ questions = self.validation_exercise.random_questions(self, number) return self._add_instance(questions)
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( )
class UserCredentials(UserCredentialsJsonSerializer, SyncableDocument, UserMixin): user = db.ReferenceField(User, required=True) local_server = db.ReferenceField('LocalServer', required=False) @property def local_server_name(self): if self.local_server: return self.local_server.name return None username = db.StringField(unique_with='local_server', required=True) password = db.StringField() @property def is_active(self): return self.user.active def has_role(self, rolename): return rolename in [r.name for r in self.user.roles] def add_visited_resource(self, resource): achievements = [] from MookAPI.services import exercise_resources, video_resources, external_video_resources, visited_resources visited_resource = visited_resources.create(credentials=self, resource=resource) if not resource.is_additional: track_achievements = self.add_started_track(resource.track) achievements.extend(track_achievements) if not exercise_resources._isinstance( resource) and not video_resources._isinstance( resource) and not external_video_resources._isinstance( resource): resource_achievements = self.add_completed_resource(resource) achievements.extend(resource_achievements) return visited_resource, achievements def add_completed_resource(self, resource): achievements = [] from MookAPI.services import completed_resources if completed_resources.find(user=self.user, resource=resource).count() == 0: completed_resource = completed_resources.create(credentials=self, resource=resource) achievements.append(completed_resource) return achievements def add_completed_skill(self, skill): achievements = [] from MookAPI.services import completed_skills if completed_skills.find(user=self.user, skill=skill, is_validated_through_test=True).count() == 0: completed_skill = completed_skills.create( credentials=self, skill=skill, is_validated_through_test=True) achievements.append(completed_skill) track = skill.track track_progress = track.user_progress(self.user) from MookAPI.services import unlocked_track_tests if unlocked_track_tests.find(user=self.user, track=track).count( ) == 0 and track_progress['current'] >= track_progress['max']: track_achievements = self.unlock_track_validation_test( track=track) achievements.extend(track_achievements) return achievements def add_started_track(self, track): achievements = [] from MookAPI.services import started_tracks if started_tracks.find(user=self.user, track=track).count() == 0: started_track = started_tracks.create(credentials=self, track=track) achievements.append(started_track) return achievements def unlock_track_validation_test(self, track): achievements = [] from MookAPI.services import unlocked_track_tests if unlocked_track_tests.find(user=self.user, track=track).count() == 0: unlocked_track_test = unlocked_track_tests.create(credentials=self, track=track) achievements.append(unlocked_track_test) return achievements def add_completed_track(self, track): achievements = [] from MookAPI.services import completed_tracks if completed_tracks.find(user=self.user, track=track).count() == 0: completed_track = completed_tracks.create(credentials=self, track=track) achievements.append(completed_track) return achievements def is_track_test_available_and_never_attempted(self, track): return self.user.is_track_test_available_and_never_attempted(track) @property def url(self, _external=False): return url_for("users.get_user_credentials", credentials_id=self.id, _external=_external) @staticmethod def hash_pass(password): """ Return the md5 hash of the password+salt """ return bcrypt.encrypt(password) def verify_pass(self, password): return bcrypt.verify(password, self.password)
class Lesson(LessonJsonSerializer, ResourceHierarchy): """ .. _Lesson: Third level of resources hierarchy. Their ascendants are Skill_ objects. Resource_ objects reference a parent Lesson_. """ ### PROPERTIES skill = db.ReferenceField('Skill') """The parent Skill_.""" ### VIRTUAL PROPERTIES @property def track(self): """Shorthand virtual property to the parent Track_ of the parent Skill_.""" return self.skill.track @property def url(self, _external=False): return url_for("hierarchy.get_lesson", lesson_id=self.id, _external=_external) @property def resources(self): """A queryset of the Resource_ objects that belong to the current Lesson_.""" return MookAPI.resources.documents.Resource.objects.order_by( 'order', 'title').filter(parent=self) @property def resources_refs(self): return [resource.to_json_dbref() for resource in self.resources] def user_progress(self, user): current = 0 for resource in self.resources: if resource.is_validated_by_user(user): current += 1 return {'current': current, 'max': len(self.resources)} @property def hierarchy(self): return [ self.track.to_json_dbref(), self.skill.to_json_dbref(), self.to_json_dbref() ] ### METHODS def siblings(self): return Lesson.objects.order_by('order', 'title').filter(skill=self.skill) def siblings_strict(self): return Lesson.objects.order_by('order', 'title').filter(skill=self.skill, id__ne=self.id) def top_level_syncable_document(self): return self.track def all_synced_documents(self, local_server=None): items = super(Lesson, self).all_synced_documents(local_server=local_server) for resource in self.resources: items.extend( resource.all_synced_documents(local_server=local_server)) return items