How to use kolibri - 10 common examples

To help you get started, we’ve selected a few kolibri examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github learningequality / kolibri / kolibri / plugins / device / api.py View on Github external
def to_representation(self, instance):
        value = super(ChannelMetadataSerializer, self).to_representation(instance)

        # if the request includes a GET param 'include_fields', add the requested calculated fields
        if "request" in self.context:

            include_fields = (
                self.context["request"].GET.get("include_fields", "").split(",")
            )

            if include_fields:

                # build querysets for the full set of channel nodes, as well as those that are unrenderable
                channel_nodes = ContentNode.objects.filter(channel_id=instance.id)
                unrenderable_nodes = channel_nodes.exclude(
                    renderable_contentnodes_without_topics_q_filter
                )

                if "total_resources" in include_fields:
                    # count the total number of renderable non-topic resources in the channel
                    # (note: it's faster to count them all and then subtract the unrenderables, of which there are fewer)
                    value["total_resources"] = (
                        channel_nodes.dedupe_by_content_id().count()
                        - unrenderable_nodes.dedupe_by_content_id().count()
                    )

                if "total_file_size" in include_fields:
                    # count the total file size of files associated with renderable content nodes
                    # (note: it's faster to count them all and then subtract the unrenderables, of which there are fewer)
                    value["total_file_size"] = total_file_size(
github learningequality / kolibri / kolibri / plugins / device / api.py View on Github external
def to_representation(self, instance):
        value = super(ChannelMetadataSerializer, self).to_representation(instance)

        # if the request includes a GET param 'include_fields', add the requested calculated fields
        if "request" in self.context:

            include_fields = (
                self.context["request"].GET.get("include_fields", "").split(",")
            )

            if include_fields:

                # build querysets for the full set of channel nodes, as well as those that are unrenderable
                channel_nodes = ContentNode.objects.filter(channel_id=instance.id)
                unrenderable_nodes = channel_nodes.exclude(
                    renderable_contentnodes_without_topics_q_filter
                )

                if "total_resources" in include_fields:
                    # count the total number of renderable non-topic resources in the channel
                    # (note: it's faster to count them all and then subtract the unrenderables, of which there are fewer)
                    value["total_resources"] = (
                        channel_nodes.dedupe_by_content_id().count()
                        - unrenderable_nodes.dedupe_by_content_id().count()
                    )

                if "total_file_size" in include_fields:
                    # count the total file size of files associated with renderable content nodes
                    # (note: it's faster to count them all and then subtract the unrenderables, of which there are fewer)
                    value["total_file_size"] = total_file_size(
github learningequality / kolibri / kolibri / core / logger / models.py View on Github external
def update_log(cls, user):
        """
        Update the current UserSessionLog for a particular user.
        """
        if user and isinstance(user, FacilityUser):
            try:
                user_session_log = cls.objects.filter(user=user).latest(
                    "last_interaction_timestamp"
                )
            except ObjectDoesNotExist:
                user_session_log = None

            if not user_session_log or timezone.now() - user_session_log.last_interaction_timestamp > timedelta(
                minutes=5
            ):
                user_session_log = cls(user=user)
            user_session_log.last_interaction_timestamp = local_now()
            user_session_log.save()
github learningequality / kolibri / kolibri / core / auth / api.py View on Github external
def users_for_facilities(self, request):
        if "member_of" not in request.GET:
            raise MissingRequiredParamsException(
                "member_of is required for this endpoint"
            )

        facility_ids = request.GET["member_of"].split(",")

        users = (
            FacilityUser.objects.filter(facility__in=facility_ids)
            .annotate(is_learner=Exists(Role.objects.filter(user=OuterRef("id"))))
            .values("id", "username", "facility_id", "is_learner", "password")
        )

        def sanitize_users(user):
            password = user.pop("password")
            user["needs_password"] = password == "NOT_SPECIFIED" or not password
            return user

        return Response(list(map(sanitize_users, users)))
github learningequality / kolibri / kolibri / core / content / management / commands / setchannelposition.py View on Github external
def handle(self, *args, **options):
        channel_id = options["channel_id"]
        position = options["pos"]
        count = ChannelMetadata.objects.count()

        try:
            target_channel = ChannelMetadata.objects.get(id=channel_id)
        except (ChannelMetadata.DoesNotExist, ValueError):
            self.stderr.write("Channel with ID {} does not exist".format(channel_id))
            sys.exit(1)

        if position < 1 or position > count:
            self.stderr.write(
                "Invalid position {}. Please choose a value between [1-{}].".format(
                    position, count
                )
            )
            sys.exit(1)

        ChannelMetadata.objects.filter(
            order__lt=target_channel.order, order__gte=position
        ).update(order=F("order") + 1)
        ChannelMetadata.objects.filter(
github learningequality / kolibri / kolibri / core / content / api.py View on Github external
def copies_count(self, request, **kwargs):
        """
        Returns the number of node copies for each content id.
        """
        content_id_string = self.request.query_params.get("content_ids")
        if content_id_string:
            content_ids = content_id_string.split(",")
            counts = (
                models.ContentNode.objects.filter_by_content_ids(content_ids)
                .filter(available=True)
                .values("content_id")
                .order_by()
                .annotate(count=Count("content_id"))
            )
        else:
            counts = 0
        return Response(counts)
github learningequality / kolibri / kolibri / core / content / serializers.py View on Github external
def to_representation(self, instance):
        # TODO: rtibbles - cleanup this for device specific serializer.
        value = super(ChannelMetadataSerializer, self).to_representation(instance)

        value.update({"num_coach_contents": get_num_coach_contents(instance.root)})

        # if the request includes a GET param 'include_fields', add the requested calculated fields
        if 'request' in self.context:

            include_fields = self.context['request'].GET.get('include_fields', '').split(',')

            if include_fields:

                # build querysets for the full set of channel nodes, as well as those that are unrenderable
                channel_nodes = ContentNode.objects.filter(channel_id=instance.id)
                unrenderable_nodes = channel_nodes.exclude(renderable_contentnodes_without_topics_q_filter)

                if 'total_resources' in include_fields:
                    # count the total number of renderable non-topic resources in the channel
                    # (note: it's faster to count them all and then subtract the unrenderables, of which there are fewer)
                    value['total_resources'] = channel_nodes.dedupe_by_content_id().count() - unrenderable_nodes.dedupe_by_content_id().count()

                if 'total_file_size' in include_fields:
                    # count the total file size of files associated with renderable content nodes
                    # (note: it's faster to count them all and then subtract the unrenderables, of which there are fewer)
                    value['total_file_size'] = _total_file_size(channel_nodes) - _total_file_size(unrenderable_nodes)

                if 'on_device_resources' in include_fields:
                    # read the precalculated total number of resources from the channel already available
                    value['on_device_resources'] = instance.total_resource_count
github learningequality / kolibri / kolibri / utils / cli.py View on Github external
logger.error(
            "There is a Kolibri server running."
            "Running updates now could cause a database error."
            "Please use `kolibri stop` and try again."
        )
        sys.exit(1)

    except server.NotRunning:
        pass

    _migrate_databases()

    run_upgrades(old_version, new_version)

    with open(version_file(), "w") as f:
        f.write(kolibri.__version__)

    from django.core.cache import caches

    cache = caches["built_files"]
    cache.clear()
github learningequality / kolibri / kolibri / core / logger / models.py View on Github external
raise ValidationError("Content summary progress out of range (0-1)")

        super(ContentSummaryLog, self).save(*args, **kwargs)


class UserSessionLog(BaseLogModel):
    """
    This model provides a record of a user session in Kolibri.
    """

    # Morango syncing settings
    morango_model_name = "usersessionlog"

    user = models.ForeignKey(FacilityUser)
    channels = models.TextField(blank=True)
    start_timestamp = DateTimeTzField(default=local_now)
    last_interaction_timestamp = DateTimeTzField(null=True, blank=True)
    pages = models.TextField(blank=True)

    @classmethod
    def update_log(cls, user):
        """
        Update the current UserSessionLog for a particular user.
        """
        if user and isinstance(user, FacilityUser):
            try:
                user_session_log = cls.objects.filter(user=user).latest(
                    "last_interaction_timestamp"
                )
            except ObjectDoesNotExist:
                user_session_log = None
github learningequality / kolibri / kolibri / core / analytics / management / commands / profile.py View on Github external
def check_start_conditions(self):
        if not SUPPORTED_OS:
            print("This OS is not yet supported")
            sys.exit(1)

        if not conf.OPTIONS["Server"]["PROFILE"]:
            print("Kolibri has not enabled profiling of its requests."
                  "To enable it, edit the Kolibri options.ini file and "
                  "add `PROFILE = true` in the [Server] section")

        if os.path.exists(PROFILE_LOCK):
            command_pid = None
            try:
                with open(PROFILE_LOCK, 'r') as f:
                    command_pid = int(f.readline())
            except (IOError, TypeError, ValueError):
                remove_lock()
            if command_pid:
                if pid_exists(command_pid):
                    print("Profile command is already running")
                    sys.exit(1)
                else: