This will return a list of unread topics for the given user from a given set of topics.

    Usage::

        {% get_unread_topics topics request.user as unread_topics %}
197045
def get_unread_topics(context, topics, user):
    
    request = context.get('request', None)
    return TrackingHandler(request=request).get_unread_topics(topics, user)
49098
def topics(self):
        
        cluster = self._client.cluster
        if self._client._metadata_refresh_in_progress and self._client._topics:
            future = cluster.request_update()
            self._client.poll(future=future)
        stash = cluster.need_all_topic_metadata
        cluster.need_all_topic_metadata = True
        future = cluster.request_update()
        self._client.poll(future=future)
        cluster.need_all_topic_metadata = stash
        return cluster.topics()
40131
def get_unread_message_count_between(parser, token):
    
    try:
        tag_name, arg = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError("%s tag requires arguments" % token.contents.split()[0])
    m = re.search(r'(.*?) and (.*?) as (\w+)', arg)
    if not m:
        raise template.TemplateSyntaxError("%s tag had invalid arguments" % tag_name)
    um_from_user, um_to_user, var_name = m.groups()
    return MessageCount(um_from_user, var_name, um_to_user)
759824
def get_topic(self):
        
        pk = self.kwargs.get(self.topic_pk_url_kwarg, None)
        if not pk:
            return
        if not hasattr(self, '_topic'):
            self._topic = get_object_or_404(Topic, pk=pk)
        return self._topic
155087
def fetchAllUsersFromThreads(self, threads):
        
        users = []
        users_to_fetch = []  # It's more efficient to fetch all users in one request
        for thread in threads:
            if thread.type == ThreadType.USER:
                if thread.uid not in [user.uid for user in users]:
                    users.append(thread)
            elif thread.type == ThreadType.GROUP:
                for user_id in thread.participants:
                    if (
                        user_id not in [user.uid for user in users]
                        and user_id not in users_to_fetch
                    ):
                        users_to_fetch.append(user_id)
        for user_id, user in self.fetchUserInfo(*users_to_fetch).items():
            users.append(user)
        return users
250632
def get_number_of_messages_in_topics(self, topics):
        

        if not isinstance(topics, list):
            topics = [topics]

        number_of_messages = 0
        for t in topics:
            part = self.get_kafka_partitions_for_topic(topic=t)
            Partitions = map(lambda p: TopicPartition(topic=t, partition=p), part)
            number_of_messages += self.get_number_of_messages_in_topicpartition(Partitions)

        return number_of_messages
555648
def get_all_messages_in_thread(self, participant_id, thread_id, check_who_read=True):
        
        try:
            messages = Message.objects.filter(thread__id=thread_id).\
                order_by('-id').\
                select_related('thread').\
                prefetch_related('thread__participation_set', 'thread__participation_set__participant')
        except Exception:
            return Message.objects.none()

        messages = self.check_who_read(messages)
        return messages
826852
public static function get_unread_conversation_counts(int $userid) : array {
        global $DB;

        // Get all conversations the user is in, and check unread.
        $unreadcountssql = 'SELECT conv.id, conv.type, indcounts.unreadcount
                              FROM {message_conversations} conv
                        INNER JOIN (
                                      SELECT m.conversationid, count(m.id) as unreadcount
                                        FROM {messages} m
                                  INNER JOIN {message_conversations} mc
                                          ON mc.id = m.conversationid
                                  INNER JOIN {message_conversation_members} mcm
                                          ON m.conversationid = mcm.conversationid
                                   LEFT JOIN {message_user_actions} mua
                                          ON (mua.messageid = m.id AND mua.userid = ? AND
                                             (mua.action = ? OR mua.action = ?))
                                       WHERE mcm.userid = ?
                                         AND m.useridfrom != ?
                                         AND mua.id is NULL
                                    GROUP BY m.conversationid
                                   ) indcounts
                                ON indcounts.conversationid = conv.id
                             WHERE conv.enabled = 1';

        $unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, self::MESSAGE_ACTION_DELETED,
            $userid, $userid]);

        // Get favourites, so we can track these separately.
        $service = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
        $favouriteconversations = $service->find_favourites_by_type('core_message', 'message_conversations');
        $favouriteconvids = array_flip(array_column($favouriteconversations, 'itemid'));

        // Assemble the return array.
        $counts = ['favourites' => 0, 'types' => [
            self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL => 0,
            self::MESSAGE_CONVERSATION_TYPE_GROUP => 0,
            self::MESSAGE_CONVERSATION_TYPE_SELF => 0
        ]];
        foreach ($unreadcounts as $convid => $info) {
            if (isset($favouriteconvids[$convid])) {
                $counts['favourites']++;
                continue;
            }
            $counts['types'][$info->type]++;
        }

        return $counts;
    }
475534
def list_comments(self, topic_id, start=0):
        
        xml = self.api.xml(API_GROUP_GET_TOPIC % topic_id, params={'start': start})
        xml_results = xml.xpath('//ul[@id="comments"]/li')
        results = []
        for item in xml_results:
            try:
                author_avatar = item.xpath('.//img/@src')[0]
                author_url = item.xpath('.//div[@class="user-face"]/a/@href')[0]
                author_alias = slash_right(author_url)
                author_signature = item.xpath('.//h4/text()')[1].strip()
                author_nickname = item.xpath('.//h4/a/text()')[0].strip()
                created_at = item.xpath('.//h4/span/text()')[0].strip()
                content = etree.tostring(item.xpath('.//div[@class="reply-doc content"]/p')[0]).decode('utf8').strip()
                cid = item.get('id')
                results.append({
                    'id': cid,
                    'author_avatar': author_avatar,
                    'author_url': author_url,
                    'author_alias': author_alias,
                    'author_signature': author_signature,
                    'author_nickname': author_nickname,
                    'created_at': created_at,
                    'content': unescape(content),
                })
            except Exception as e:
                self.api.logger.exception('parse comment exception: %s' % e)
        return build_list_result(results, xml)
534173
def get_all_jobs(user, topic_id=None):
    
    # get the diverse parameters
    args = schemas.args(flask.request.args.to_dict())

    # build the query thanks to the QueryBuilder class
    query = v1_utils.QueryBuilder(_TABLE, args, _JOBS_COLUMNS)

    # add extra conditions for filtering

    # # If not admin nor rh employee then restrict the view to the team
    if user.is_not_super_admin() and not user.is_read_only_user():
        query.add_extra_condition(
            sql.or_(
                _TABLE.c.team_id.in_(user.teams_ids),
                _TABLE.c.team_id.in_(user.child_teams_ids)))

    # # If topic_id not None, then filter by topic_id
    if topic_id is not None:
        query.add_extra_condition(_TABLE.c.topic_id == topic_id)

    # # Get only the non archived jobs
    query.add_extra_condition(_TABLE.c.state != 'archived')

    nb_rows = query.get_number_of_rows()
    rows = query.execute(fetchall=True)
    rows = v1_utils.format_result(rows, _TABLE.name, args['embed'],
                                  _EMBED_MANY)

    return flask.jsonify({'jobs': rows, '_meta': {'count': nb_rows}})
745265
def unpause_topic(self, topic):
        """"""
        nsq.assert_valid_topic_name(topic)
        return self._request('POST', '/topic/unpause', fields={'topic': topic})
1305566
def user_topic_ids(user):
    """"""

    if user.is_super_admin() or user.is_read_only_user():
        query = sql.select([models.TOPICS])
    else:
        query = (sql.select([models.JOINS_TOPICS_TEAMS.c.topic_id])
                 .select_from(
                     models.JOINS_TOPICS_TEAMS.join(
                         models.TOPICS, sql.and_(models.JOINS_TOPICS_TEAMS.c.topic_id == models.TOPICS.c.id,  # noqa
                                                 models.TOPICS.c.state == 'active'))  # noqa
                  ).where(
                      sql.or_(models.JOINS_TOPICS_TEAMS.c.team_id.in_(user.teams_ids),  # noqa
                              models.JOINS_TOPICS_TEAMS.c.team_id.in_(user.child_teams_ids))))  # noqa

    rows = flask.g.db_conn.execute(query).fetchall()
    return [str(row[0]) for row in rows]
1006498
def discussions_for(user, only_open=True):
    '''
    
    '''
    # Only fetch required fields for discussion filtering (id and slug)
    # Greatly improve performances and memory usage
    datasets = Dataset.objects.owned_by(user.id, *user.organizations).only('id', 'slug')
    reuses = Reuse.objects.owned_by(user.id, *user.organizations).only('id', 'slug')

    qs = Discussion.objects(subject__in=list(datasets) + list(reuses))
    if only_open:
        qs = qs(closed__exists=False)
    return qs
1045693
def mark_topics_read(self, request, pk):
        
        track_handler.mark_forums_read([self.forum, ], request.user)
        messages.success(request, self.success_message)
        return HttpResponseRedirect(self.get_forum_url())
424439
def issues_notifications(user):
    ''''''
    notifications = []

    # Only fetch required fields for notification serialization
    # Greatly improve performances and memory usage
    qs = issues_for(user).only('id', 'title', 'created', 'subject')

    # Do not dereference subject (so it's a DBRef)
    # Also improve performances and memory usage
    for issue in qs.no_dereference():
        notifications.append((issue.created, {
            'id': issue.id,
            'title': issue.title,
            'subject': {
                'id': issue.subject['_ref'].id,
                'type': issue.subject['_cls'].lower(),
            }
        }))

    return notifications
606749
def list_conversations(self, filter=None, filter_mode=None, include=None, include_all_conversation_ids=None, interleave_submissions=None, scope=None):
        
        path = {}
        data = {}
        params = {}

        # OPTIONAL - scope
        """When set, only return conversations of the specified type. For example,
        set to "unread" to return only conversations that haven't been read.
        The default behavior is to return all non-archived conversations (i.e.
        read and unread)."""
        if scope is not None:
            self._validate_enum(scope, ["unread", "starred", "archived"])
            params["scope"] = scope

        # OPTIONAL - filter
        """When set, only return conversations for the specified courses, groups
        or users. The id should be prefixed with its type, e.g. "user_123" or
        "course_456". Can be an array (by setting "filter[]") or single value
        (by setting "filter")"""
        if filter is not None:
            params["filter"] = filter

        # OPTIONAL - filter_mode
        """When filter[] contains multiple filters, combine them with this mode,
        filtering conversations that at have at least all of the contexts ("and")
        or at least one of the contexts ("or")"""
        if filter_mode is not None:
            self._validate_enum(filter_mode, ["and", "or", "default or"])
            params["filter_mode"] = filter_mode

        # OPTIONAL - interleave_submissions
        """(Obsolete) Submissions are no
        longer linked to conversations. This parameter is ignored."""
        if interleave_submissions is not None:
            params["interleave_submissions"] = interleave_submissions

        # OPTIONAL - include_all_conversation_ids
        """Default is false. If true,
        the top-level element of the response will be an object rather than
        an array, and will have the keys "conversations" which will contain the
        paged conversation data, and "conversation_ids" which will contain the
        ids of all conversations under this scope/filter in the same order."""
        if include_all_conversation_ids is not None:
            params["include_all_conversation_ids"] = include_all_conversation_ids

        # OPTIONAL - include
        """"participant_avatars":: Optionally include an "avatar_url" key for each user participanting in the conversation"""
        if include is not None:
            self._validate_enum(include, ["participant_avatars"])
            params["include"] = include

        self.logger.debug("GET /api/v1/conversations with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/conversations".format(**path), data=data, params=params, all_pages=True)
1290317
def get_topics(self):
        
        headers, data = self._requester.requestJsonAndCheck(
            "GET",
            self.url + "/topics",
            headers={'Accept': Consts.mediaTypeTopicsPreview}
        )
        return data['names']