Beispiel #1
0
def do_render_markdown(
    message: Message,
    content: str,
    realm: Realm,
    sent_by_bot: bool,
    translate_emoticons: bool,
    realm_alert_words_automaton: Optional[ahocorasick.Automaton] = None,
    mention_data: Optional[MentionData] = None,
    email_gateway: bool = False,
) -> str:
    """Return HTML for given Markdown. Markdown may add properties to the
    message object such as `mentions_user_ids`, `mentions_user_group_ids`, and
    `mentions_wildcard`.  These are only on this Django object and are not
    saved in the database.
    """

    message.mentions_wildcard = False
    message.mentions_user_ids = set()
    message.mentions_user_group_ids = set()
    message.alert_words = set()
    message.links_for_preview = set()
    message.user_ids_with_alert_words = set()

    # DO MAIN WORK HERE -- call markdown_convert to convert
    rendered_content = markdown_convert(
        content,
        realm_alert_words_automaton=realm_alert_words_automaton,
        message=message,
        message_realm=realm,
        sent_by_bot=sent_by_bot,
        translate_emoticons=translate_emoticons,
        mention_data=mention_data,
        email_gateway=email_gateway,
    )
    return rendered_content
Beispiel #2
0
def render_markdown(
    message: Message,
    content: str,
    realm: Optional[Realm] = None,
    realm_alert_words_automaton: Optional[ahocorasick.Automaton] = None,
    mention_data: Optional[MentionData] = None,
    email_gateway: bool = False,
) -> MessageRenderingResult:
    """
    This is basically just a wrapper for do_render_markdown.
    """

    if realm is None:
        realm = message.get_realm()

    sender = message.sender
    sent_by_bot = sender.is_bot
    translate_emoticons = sender.translate_emoticons

    rendering_result = markdown_convert(
        content,
        realm_alert_words_automaton=realm_alert_words_automaton,
        message=message,
        message_realm=realm,
        sent_by_bot=sent_by_bot,
        translate_emoticons=translate_emoticons,
        mention_data=mention_data,
        email_gateway=email_gateway,
    )

    return rendering_result
Beispiel #3
0
    def test_update_profile_data_successfully(self) -> None:
        self.login('iago')
        realm = get_realm('zulip')
        fields = [
            ('Phone number', '*short* text data'),
            ('Biography', '~~short~~ **long** text data'),
            ('Favorite food', 'long short text data'),
            ('Favorite editor', 'vim'),
            ('Birthday', '1909-3-5'),
            ('Favorite website', 'https://zulip.com'),
            ('Mentor', [self.example_user("cordelia").id]),
            ('GitHub', 'zulip-mobile'),
        ]

        data = []
        for i, field_value in enumerate(fields):
            name, value = field_value
            field = CustomProfileField.objects.get(name=name, realm=realm)
            data.append({
                'id': field.id,
                'value': value,
                'field': field,
            })

        # Update value of field
        result = self.client_patch(
            "/json/users/me/profile_data",
            {"data": orjson.dumps([{"id": f["id"], "value": f["value"]} for f in data]).decode()},
        )
        self.assert_json_success(result)

        iago = self.example_user('iago')
        expected_value = {f['id']: f['value'] for f in data}
        expected_rendered_value: Dict[Union[int, float, str, None], Union[str, None]] = {}
        for f in data:
            if f['field'].is_renderable():
                expected_rendered_value[f['id']] = markdown_convert(f['value'])
            else:
                expected_rendered_value[f['id']] = None

        for field_dict in iago.profile_data:
            self.assertEqual(field_dict['value'], expected_value[field_dict['id']])
            self.assertEqual(field_dict['rendered_value'], expected_rendered_value[field_dict['id']])
            for k in ['id', 'type', 'name', 'field_data']:
                self.assertIn(k, field_dict)

        # Update value of one field.
        field = CustomProfileField.objects.get(name='Biography', realm=realm)
        data = [{
            'id': field.id,
            'value': 'foobar',
        }]

        result = self.client_patch("/json/users/me/profile_data",
                                   {'data': orjson.dumps(data).decode()})
        self.assert_json_success(result)
        for field_dict in iago.profile_data:
            if field_dict['id'] == field.id:
                self.assertEqual(field_dict['value'], 'foobar')
Beispiel #4
0
def filter_and_render_string(input: str) -> str:
    # Run through the markdown engine so that links will work
    output = markdown_convert(
        input,
        message_realm=get_realm('zulip'),
    )
    # Remove p tags from render output, so the options do not create new lines
    output = re.sub(r'<\/*p>', '', output)
    return output
Beispiel #5
0
def render_stream_description(text: str) -> str:
    return markdown_convert(text, no_previews=True).rendered_content
    def test_update_profile_data_successfully(self) -> None:
        self.login("iago")
        realm = get_realm("zulip")
        fields = [
            ("Phone number", "*short* text data"),
            ("Biography", "~~short~~ **long** text data"),
            ("Favorite food", "long short text data"),
            ("Favorite editor", "vim"),
            ("Birthday", "1909-03-05"),
            ("Favorite website", "https://zulip.com"),
            ("Mentor", [self.example_user("cordelia").id]),
            ("GitHub", "zulip-mobile"),
        ]

        data = []
        for i, field_value in enumerate(fields):
            name, value = field_value
            field = CustomProfileField.objects.get(name=name, realm=realm)
            data.append({
                "id": field.id,
                "value": value,
                "field": field,
            })

        # Update value of field
        result = self.client_patch(
            "/json/users/me/profile_data",
            {
                "data":
                orjson.dumps([{
                    "id": f["id"],
                    "value": f["value"]
                } for f in data]).decode()
            },
        )
        self.assert_json_success(result)

        iago = self.example_user("iago")
        expected_value = {f["id"]: f["value"] for f in data}
        expected_rendered_value: Dict[Union[int, float, str, None],
                                      Union[str, None]] = {}
        for f in data:
            if f["field"].is_renderable():
                expected_rendered_value[f["id"]] = markdown_convert(f["value"])
            else:
                expected_rendered_value[f["id"]] = None

        for field_dict in iago.profile_data:
            self.assertEqual(field_dict["value"],
                             expected_value[field_dict["id"]])
            self.assertEqual(field_dict["rendered_value"],
                             expected_rendered_value[field_dict["id"]])
            for k in ["id", "type", "name", "field_data"]:
                self.assertIn(k, field_dict)

        # Update value of one field.
        field = CustomProfileField.objects.get(name="Biography", realm=realm)
        data = [{
            "id": field.id,
            "value": "foobar",
        }]

        result = self.client_patch("/json/users/me/profile_data",
                                   {"data": orjson.dumps(data).decode()})
        self.assert_json_success(result)
        for field_dict in iago.profile_data:
            if field_dict["id"] == field.id:
                self.assertEqual(field_dict["value"], "foobar")
Beispiel #7
0
def get_realm_rendered_description(realm: Realm) -> str:
    realm_description_raw = realm.description or "The coolest place in the universe."
    return markdown_convert(realm_description_raw,
                            message_realm=realm,
                            no_previews=True)