<fim-prefix>  if not is_active_subscriber(user_profile=user_profile,
                                    recipient=recipient):
            return json_error(_("Invalid stream id"))

    result = get_topic_history_for_stream(
        user_profile=user_profile,
        recipient=recipient,
    )

    # Our data structure here is a list of tuples of
    # (topic name, unread count), and it's reverse chronological,
    # so the most recent topic is the first element of the list.
    return json_success(dict(topics=result))


@authenticated_json_post_view
@has_request_variables
def json_stream_exists(request, user_profile, stream=REQ(),
                       autosubscribe=REQ(default=False)):
    # type: (HttpRequest, UserProfile, Text, bool) -> HttpResponse
    if not valid_stream_name(stream):
        return json_error(_("Invalid characters in stream name"))
    try:
        stream_id = Stream.objects.get(realm=user_profile.realm, name=stream).id
    except Stream.DoesNotExist:
        stream_id = None
    return stream_exists_backend(request, user_profile, stream_id, autosubscribe)

def stream_exists_backend(request, user_profile, stream_id, autosubscribe):
    # type: (HttpRequest, UserProfile, int, bool) -> HttpResponse
    try:
        stream = get_and_validate_stream_by_id(stream_id, user_profile.realm)
    except JsonableError:
        stream = None
    result = {"exists": bool(stream)}
    if stream is not None:
        recipient = get_recipient(Recipient.STREAM, stream.id)
        # BUG: CWE-863 Incorrect Authorization
        # if autosubscribe:
        # FIXED:
  <fim-middle>      if not stream.invite_only and autosubscribe:
            bulk_add_subscriptions([stream], [user_profile])
        result["subscribed"] = is_active_subscriber(
            user_profile=user_profil<fix-suffix>e,
            recipient=recipient)

        return json_success(result) # results are ignored for HEAD requests
    return json_response(data=result, status=404)

def get_and_validate_stream_by_id(stream_id, realm):
    # type: (int, Realm) -> Stream
    try:
        stream = Stream.objects.get(pk=stream_id, realm_id=realm.id)
    except Stream.DoesNotExist:
        raise JsonableError(_("Invalid stream id"))
    return stream

@has_request_variables
def json_get_stream_id(request, user_profile, stream=REQ()):
    # type: (HttpRequest, UserProfile, Text) -> HttpResponse
    try:
        stream_id = Stream.objects.get(realm=user_profile.realm, name=stream).id
    except Stream.DoesNotExist:
        return json_error(_("No such stream name"))
    return json_success({'stream_id': stream_id})

def get_subscription_or_die(stream_name, user_profile):
    # type: (Text, UserProfile) -> Subscription
    stream = get_stream(stream_name, user_profile.realm)
    if not stream:
        raise Jso<|endoftext|>