Example #1
0
def json_stream_exists(
    request: HttpRequest,
    user_profile: UserProfile,
    stream_name: str = REQ("stream"),
    autosubscribe: bool = REQ(json_validator=check_bool, default=False),
) -> HttpResponse:
    check_stream_name(stream_name)

    try:
        (stream, sub) = access_stream_by_name(user_profile, stream_name)
    except JsonableError as e:
        raise ResourceNotFoundError(e.msg)

    # access_stream functions return a subscription if and only if we
    # are already subscribed.
    result = {"subscribed": sub is not None}

    # If we got here, we're either subscribed or the stream is public.
    # So if we're not yet subscribed and autosubscribe is enabled, we
    # should join.
    if sub is None and autosubscribe:
        bulk_add_subscriptions(user_profile.realm, [stream], [user_profile],
                               acting_user=user_profile)
        result["subscribed"] = True

    return json_success(request,
                        data=result)  # results are ignored for HEAD requests
Example #2
0
def do_delete_draft(draft_id: int, user_profile: UserProfile) -> None:
    """Delete a draft belonging to a particular user."""
    try:
        draft_object = Draft.objects.get(id=draft_id,
                                         user_profile=user_profile)
    except Draft.DoesNotExist:
        raise ResourceNotFoundError(_("Draft does not exist"))
    draft_object.delete()
Example #3
0
def delete_draft(request: HttpRequest, user_profile: UserProfile,
                 draft_id: int) -> HttpResponse:
    try:
        draft_object = Draft.objects.get(id=draft_id,
                                         user_profile=user_profile)
    except Draft.DoesNotExist:
        raise ResourceNotFoundError(_("Draft does not exist"))

    draft_object.delete()
    return json_success()
Example #4
0
def do_delete_draft(draft_id: int, user_profile: UserProfile) -> None:
    """Delete a draft belonging to a particular user."""
    try:
        draft_object = Draft.objects.get(id=draft_id,
                                         user_profile=user_profile)
    except Draft.DoesNotExist:
        raise ResourceNotFoundError(_("Draft does not exist"))

    draft_id = draft_object.id
    draft_object.delete()

    event = {"type": "drafts", "op": "remove", "draft_id": draft_id}
    send_event(user_profile.realm, event, [user_profile.id])
Example #5
0
def get_fixtures(
    request: HttpResponse, integration_name: str = REQ()) -> HttpResponse:
    valid_integration_name = get_valid_integration_name(integration_name)
    if not valid_integration_name:
        raise ResourceNotFoundError(
            f'"{integration_name}" is not a valid webhook integration.')

    fixtures = {}
    fixtures_dir = os.path.join(
        ZULIP_PATH, f"zerver/webhooks/{valid_integration_name}/fixtures")
    if not os.path.exists(fixtures_dir):
        msg = (
            'The integration "{valid_integration_name}" does not have fixtures.'
        ).format(valid_integration_name=valid_integration_name)
        raise ResourceNotFoundError(msg)

    for fixture in os.listdir(fixtures_dir):
        fixture_path = os.path.join(fixtures_dir, fixture)
        with open(fixture_path) as f:
            body = f.read()
        try:
            body = orjson.loads(body)
        except orjson.JSONDecodeError:
            pass  # The file extension will be used to determine the type.

        headers_raw = get_fixture_http_headers(
            valid_integration_name, "".join(fixture.split(".")[:-1]))

        def fix_name(header: str) -> str:
            if header.startswith(
                    "HTTP_"):  # HTTP_ is a prefix intended for Django.
                return header[len("HTTP_"):]
            return header

        headers = {fix_name(k): v for k, v in headers_raw.items()}
        fixtures[fixture] = {"body": body, "headers": headers}

    return json_success({"fixtures": fixtures})
Example #6
0
def send_all_webhook_fixture_messages(
    request: HttpRequest, url: str = REQ(), integration_name: str = REQ()
) -> HttpResponse:
    valid_integration_name = get_valid_integration_name(integration_name)
    if not valid_integration_name:
        raise ResourceNotFoundError(
            f'"{integration_name}" is not a valid webhook integration.')

    fixtures_dir = os.path.join(
        ZULIP_PATH, f"zerver/webhooks/{valid_integration_name}/fixtures")
    if not os.path.exists(fixtures_dir):
        msg = (
            'The integration "{valid_integration_name}" does not have fixtures.'
        ).format(valid_integration_name=valid_integration_name)
        raise ResourceNotFoundError(msg)

    responses = []
    for fixture in os.listdir(fixtures_dir):
        fixture_path = os.path.join(fixtures_dir, fixture)
        with open(fixture_path) as f:
            content = f.read()
        x = fixture.split(".")
        fixture_name, fixture_format = "".join(_ for _ in x[:-1]), x[-1]
        headers = get_fixture_http_headers(valid_integration_name,
                                           fixture_name)
        if fixture_format == "json":
            is_json = True
        else:
            is_json = False
        response = send_webhook_fixture_message(url, content, is_json, headers)
        responses.append({
            "status_code": response.status_code,
            "fixture_name": fixture,
            "message": response.content.decode(),
        })
    return json_success({"responses": responses})
Example #7
0
def do_edit_draft(draft_id: int, draft_dict: Dict[str, Any],
                  user_profile: UserProfile) -> None:
    """Edit/update a single draft for a given user. Since the only place this method is being
    used from (apart from tests) is the edit_draft view, we assume that the drafts_dict is
    syntactically valid (i.e. it satisfies the draft_dict_validator)."""
    try:
        draft_object = Draft.objects.get(id=draft_id,
                                         user_profile=user_profile)
    except Draft.DoesNotExist:
        raise ResourceNotFoundError(_("Draft does not exist"))
    valid_draft_dict = further_validated_draft_dict(draft_dict, user_profile)
    draft_object.content = valid_draft_dict["content"]
    draft_object.topic = valid_draft_dict["topic"]
    draft_object.recipient = valid_draft_dict["recipient"]
    draft_object.last_edit_time = valid_draft_dict["last_edit_time"]
    draft_object.save()
Example #8
0
def edit_draft(
    request: HttpRequest,
    user_profile: UserProfile,
    draft_id: int,
    draft_dict: Dict[str, Any] = REQ("draft",
                                     json_validator=draft_dict_validator),
) -> HttpResponse:
    try:
        draft_object = Draft.objects.get(id=draft_id,
                                         user_profile=user_profile)
    except Draft.DoesNotExist:
        raise ResourceNotFoundError(_("Draft does not exist"))

    valid_draft_dict = further_validated_draft_dict(draft_dict, user_profile)
    draft_object.content = valid_draft_dict["content"]
    draft_object.topic = valid_draft_dict["topic"]
    draft_object.recipient = valid_draft_dict["recipient"]
    draft_object.last_edit_time = valid_draft_dict["last_edit_time"]
    draft_object.save()

    return json_success()