Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

markdown: Render inline audio files using the `![title](url)` syntax.

Rohan Gudimetla26abfc4d919d
diff --git a/api_docs/changelog.md b/api_docs/changelog.md
index 79df10d4b77..e4d241bbc0b 100644
--- a/api_docs/changelog.md
+++ b/api_docs/changelog.md
@@ -20,6 +20,11 @@ format used by the Zulip server that they are interacting with.
## Changes in Zulip 11.0
+**Feature level 405**
+
+* [Message formatting](/api/message-formatting): Added new HTML
+ formatting for uploaded audio files generating a player experience.
+
**Feature level 404**
* [`GET /users/me/subscriptions`](/api/get-subscriptions),
diff --git a/api_docs/message-formatting.md b/api_docs/message-formatting.md
index 260d6379a46..78f3033fac2 100644
--- a/api_docs/message-formatting.md
+++ b/api_docs/message-formatting.md
@@ -243,11 +243,12 @@ assume that messages sent prior to the introduction of thumbnailing
have been re-rendered to use the new format or have thumbnails
available.
-## Video previews
+## Video embeddings and previews
-When a Zulip message is sent linking to an uploaded video, Zulip will
+When a Zulip message is sent linking to an uploaded video, Zulip may
generate a video preview element with the following format.
+
``` html
<div class="message_inline_image message_inline_video">
<a href="/user_uploads/path/to/video.mp4">
@@ -257,6 +258,40 @@ generate a video preview element with the following format.
</div>
```
+## Audio Players
+
+When the Markdown media syntax is used with an uploaded file with an
+audio `Content-Type`, Zulip will generate an HTML5 `<audio>` player
+element. Supported MIME types are currently `audio/aac`, `audio/flac`,
+`audio/mpeg`, and `audio/wav`.
+
+For example, `[file.mp3](/user_uploads/path/to/file.mp3)` renders as:
+
+``` html
+<audio controls preload="metadata"
+ src="/user_uploads/path/to/file.mp3" title="file.mp3">
+</audio>
+```
+
+If the Zulip server has rewritten the URL of the audio file, it will
+provide the URL in a `data-original-url` parameter. The Zulip server
+does this for all non-uploaded file audio URLs.
+
+``` html
+<audio controls preload="metadata"
+ data-original-url="https://example.com/path/to/original/file.mp3"
+ src="https://zulipcdn.example.com/path/to/playable/file.mp3" title="file.mp3">
+</audio>
+```
+
+Clients that cannot render an audio player are recommended to convert
+audio elements into a link to the original URL.
+
+The Zulip server does not validate whether uploaded files with an
+audio `Content-Type` are actually playable.
+
+**Changes**: New in Zulip 11.0 (feature level ZF-79b5ee.md).
+
## Mentions and silent mentions
Zulip markup supports [mentioning](/help/mention-a-user-or-group)
diff --git a/version.py b/version.py
index 401f68f3083..47b960af586 100644
--- a/version.py
+++ b/version.py
@@ -34,7 +34,7 @@ DESKTOP_WARNING_VERSION = "5.9.3"
# new level means in api_docs/changelog.md, as well as "**Changes**"
# entries in the endpoint's documentation in `zulip.yaml`.
-API_FEATURE_LEVEL = 404
+API_FEATURE_LEVEL = 405
# Bump the minor PROVISION_VERSION to indicate that folks should provision
# only when going from an old version of the code to a newer version. Bump
diff --git a/web/src/markdown.ts b/web/src/markdown.ts
index d7c4a79e079..32f6686e856 100644
--- a/web/src/markdown.ts
+++ b/web/src/markdown.ts
@@ -23,10 +23,10 @@ import * as util from "./util.ts";
// If we see preview-related syntax in our content, we will need the
// backend to render it.
const preview_regexes = [
- // Inline image and video previews, check for contiguous chars ending in image and video suffix
+ // Inline media previews, check for contiguous chars ending in media suffix
// To keep the below regexes simple, split them out for the end-of-message case
- /\S*(?:\.bmp|\.gif|\.jpg|\.jpeg|\.png|\.webp|\.mp4|\.webm)\)?(\s+|$)/m,
+ /\S*(?:\.bmp|\.gif|\.jpg|\.jpeg|\.png|\.webp|\.mp4|\.webm|\.aac|\.flac|\.mp3|\.mpeg|\.wav)\)?(\s+|$)/m,
// Twitter and youtube links are given previews
diff --git a/zerver/actions/message_edit.py b/zerver/actions/message_edit.py
index 1e490acfb60..829ff1d1208 100644
--- a/zerver/actions/message_edit.py
+++ b/zerver/actions/message_edit.py
@@ -1734,7 +1734,7 @@ def re_thumbnail(
message.rendered_content,
enqueue=enqueue,
lock=True,
- )
+ ).image_metadata
new_content, _ = rewrite_thumbnailed_images(
message.rendered_content,
diff --git a/zerver/actions/message_send.py b/zerver/actions/message_send.py
index c49b94ae7b9..9613294b673 100644
--- a/zerver/actions/message_send.py
+++ b/zerver/actions/message_send.py
@@ -904,7 +904,7 @@ def do_send_messages(
lock=True,
enqueue=False,
path_ids=list(send_request.rendering_result.thumbnail_spinners),
- )
+ ).image_metadata
new_rendered_content = rewrite_thumbnailed_images(
send_request.message.rendered_content, previews
)[0]
diff --git a/zerver/lib/markdown/__init__.py b/zerver/lib/markdown/__init__.py
index 1f362af004e..c39975bf56c 100644
--- a/zerver/lib/markdown/__init__.py
+++ b/zerver/lib/markdown/__init__.py
@@ -54,11 +54,12 @@ from zerver.lib.mention import (
MentionData,
get_user_group_mention_display_name,
)
+from zerver.lib.mime_types import AUDIO_INLINE_MIME_TYPES, guess_type
from zerver.lib.outgoing_http import OutgoingSession
from zerver.lib.subdomains import is_static_or_current_realm_url
from zerver.lib.tex import render_tex
from zerver.lib.thumbnail import (
- MarkdownImageMetadata,
+ AttachmentData,
get_user_upload_previews,
rewrite_thumbnailed_images,
)
@@ -133,7 +134,7 @@ class DbData:
stream_names: dict[str, int]
topic_info: dict[ChannelTopicInfo, int | None]
translate_emoticons: bool
- user_upload_previews: dict[str, MarkdownImageMetadata]
+ user_upload_previews: AttachmentData
# Format version of the Markdown rendering; stored along with rendered
@@ -683,8 +684,8 @@ class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
# We should have pulled the preview data for this image
# (even if that's "no preview yet") from the database
# before rendering; is_image should have enforced that.
- assert path_id in self.zmd.zulip_db_data.user_upload_previews
- metadata = self.zmd.zulip_db_data.user_upload_previews[path_id]
+ assert path_id in self.zmd.zulip_db_data.user_upload_previews.image_metadata
+ metadata = self.zmd.zulip_db_data.user_upload_previews.image_metadata[path_id]
# Insert a placeholder image spinner. We post-process
# this content (see rewrite_thumbnailed_images in
@@ -796,7 +797,7 @@ class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
# as a valid image type which libvips handles.
if url.startswith("/user_uploads/") and self.zmd.zulip_db_data:
path_id = url.removeprefix("/user_uploads/")
- return path_id in self.zmd.zulip_db_data.user_upload_previews
+ return path_id in self.zmd.zulip_db_data.user_upload_previews.image_metadata
return any(parsed_url.path.lower().endswith(ext) for ext in IMAGE_EXTENSIONS)
@@ -2289,6 +2290,85 @@ class LinkInlineProcessor(markdown.inlinepatterns.LinkInlineProcessor):
return None, None, None
+class AudioInlineProcessor(markdown.inlinepatterns.LinkInlineProcessor):
+ def __init__(self, pattern: str, zmd: "ZulipMarkdown") -> None:
+ super().__init__(pattern, zmd)
+ self.zmd = zmd
+
+ def is_supported_audio_url(self, url: str) -> bool:
+ url_type = guess_type(url)[0]
+ return url_type in AUDIO_INLINE_MIME_TYPES
+
+ def maybe_audio_element(self, src: str, title: str) -> Element | None:
+ el = Element("audio")
+ el.set("src", src)
+ title = title.strip()
+ if title:
+ el.set("title", title)
+
+ return self.zulip_specific_src_changes(el)
+
+ def zulip_specific_src_changes(self, el: Element) -> None | Element:
+ src = el.get("src")
+ assert src is not None
+
+ # Sanitize URL or don't parse link. See linkify_tests in markdown_test_cases for banned syntax.
+ src = sanitize_url(self.unescape(src.strip()))
+ if src is None:
+ return None # no-op; the link is not processed.
+
+ # Rewrite local links to be relative
+ db_data: DbData | None = self.zmd.zulip_db_data
+ src = rewrite_local_links_to_relative(db_data, src)
+ maybe_add_attachment_path_id(src, self.zmd)
+
+ if src.startswith("/user_uploads/") and db_data:
+ path_id = src.removeprefix("/user_uploads/")
+
+ # We should have pulled the previewable path ids from
+ # from the database before rendering; If the path_id
+ # is not found, then it is not a previewable MIME type.
+ if path_id not in db_data.user_upload_previews.audio_path_ids:
+ return None
+
+ elif not self.is_supported_audio_url(src):
+ return None
+
+ # Make changes to <audio> tag attributes
+ if is_static_or_current_realm_url(src, self.zmd.zulip_realm):
+ # Don't rewrite audios on our own site (e.g. user uploads).
+ el.set("src", src)
+ else:
+ el.set("src", get_camo_url(src))
+
+ el.set("controls", "controls")
+ el.set("preload", "metadata")
+
+ if src != el.get("src"):
+ el.set("data-original-url", src)
+
+ return el
+
+ @override
+ def handleMatch( # type: ignore[override] # https://github.com/python/mypy/issues/10197
+ self, m: Match[str], data: str
+ ) -> tuple[Element | str | None, int | None, int | None]:
+ title, index, handled = self.getText(data, m.end(0))
+ if not handled:
+ return None, None, None
+
+ src, non_src, index, handled = self.getLink(data, index)
+ if not handled or non_src is not None:
+ return None, None, None
+
+ el = self.maybe_audio_element(src, title)
+
+ if el is not None:
+ return el, m.start(0), index
+
+ return None, None, None
+
+
def get_sub_registry(r: markdown.util.Registry[T], keys: list[str]) -> markdown.util.Registry[T]:
# Registry is a new class added by Python-Markdown to replace OrderedDict.
# Since Registry doesn't support .keys(), it is easier to make a new
@@ -2452,6 +2532,7 @@ class ZulipMarkdown(markdown.Markdown):
UserGroupMentionPattern(mention.USER_GROUP_MENTIONS_RE, self), "usergroupmention", 65
)
reg.register(LinkInlineProcessor(markdown.inlinepatterns.LINK_RE, self), "link", 60)
+ reg.register(AudioInlineProcessor(markdown.inlinepatterns.IMAGE_LINK_RE, self), "audio", 57)
reg.register(AutoLink(get_web_link_regex(), self), "autolink", 55)
# Reserve priority 45-54 for linkifiers
reg = self.register_linkifiers(reg)
@@ -2843,7 +2924,7 @@ def do_convert(
# Post-process the result with the rendered image previews:
if user_upload_previews is not None:
content_with_thumbnails, thumbnail_spinners = rewrite_thumbnailed_images(
- rendering_result.rendered_content, user_upload_previews
+ rendering_result.rendered_content, user_upload_previews.image_metadata
)
rendering_result.thumbnail_spinners = thumbnail_spinners
if content_with_thumbnails is not None:
diff --git a/zerver/lib/mime_types.py b/zerver/lib/mime_types.py
index f835d2ed42a..8c8b8edc095 100644
--- a/zerver/lib/mime_types.py
+++ b/zerver/lib/mime_types.py
@@ -22,13 +22,21 @@ for mime_type, extension in EXTRA_MIME_TYPES:
add_type(mime_type, extension)
-INLINE_MIME_TYPES = [
- "application/pdf",
+AUDIO_INLINE_MIME_TYPES = [
"audio/aac",
"audio/flac",
- "audio/mp4",
"audio/mpeg",
"audio/wav",
+]
+
+INLINE_MIME_TYPES = [
+ *AUDIO_INLINE_MIME_TYPES,
+ "application/pdf",
+ # We don't want to include `audio/mp4` and `audio/webm` in the
+ # `AUDIO_INLINE_MIME` TYPES because despite their ability to be
+ # used for both audio and video, they happen to be parsed only
+ # in their video form.
+ "audio/mp4",
"audio/webm",
"image/apng",
"image/avif",
diff --git a/zerver/lib/thumbnail.py b/zerver/lib/thumbnail.py
index e9a677ecc3a..45634166c21 100644
--- a/zerver/lib/thumbnail.py
+++ b/zerver/lib/thumbnail.py
@@ -12,9 +12,9 @@ from django.utils.translation import gettext as _
from typing_extensions import Self, override
from zerver.lib.exceptions import ErrorCode, JsonableError
-from zerver.lib.mime_types import INLINE_MIME_TYPES
+from zerver.lib.mime_types import AUDIO_INLINE_MIME_TYPES, INLINE_MIME_TYPES
from zerver.lib.queue import queue_event_on_commit
-from zerver.models import ImageAttachment
+from zerver.models import Attachment, ImageAttachment
DEFAULT_AVATAR_SIZE = 100
MEDIUM_AVATAR_SIZE = 500
@@ -408,19 +408,28 @@ class MarkdownImageMetadata:
transcoded_image: StoredThumbnailFormat | None = None
+@dataclass
+class AttachmentData:
+ audio_path_ids: set[str]
+ image_metadata: dict[str, MarkdownImageMetadata]
+
+
def get_user_upload_previews(
realm_id: int,
content: str,
lock: bool = False,
enqueue: bool = True,
path_ids: list[str] | None = None,
-) -> dict[str, MarkdownImageMetadata]:
+) -> AttachmentData:
if path_ids is None:
path_ids = re.findall(r"/user_uploads/(\d+/[/\w.-]+)", content)
if not path_ids:
- return {}
+ return AttachmentData(
+ audio_path_ids=set(),
+ image_metadata={},
+ )
- upload_preview_data: dict[str, MarkdownImageMetadata] = {}
+ image_metadata: dict[str, MarkdownImageMetadata] = {}
image_attachments = ImageAttachment.objects.filter(
realm_id=realm_id, path_id__in=path_ids
@@ -432,7 +441,7 @@ def get_user_upload_previews(
# Image exists, and header of it parsed as a valid image,
# but has not been thumbnailed yet; we will render a
# spinner.
- upload_preview_data[image_attachment.path_id] = MarkdownImageMetadata(
+ image_metadata[image_attachment.path_id] = MarkdownImageMetadata(
url=None,
is_animated=False,
original_width_px=image_attachment.original_width_px,
@@ -450,7 +459,7 @@ def get_user_upload_previews(
queue_event_on_commit("thumbnail", {"id": image_attachment.id})
else:
url, is_animated = get_default_thumbnail_url(image_attachment)
- upload_preview_data[image_attachment.path_id] = MarkdownImageMetadata(
+ image_metadata[image_attachment.path_id] = MarkdownImageMetadata(
url=url,
is_animated=is_animated,
original_width_px=image_attachment.original_width_px,
@@ -458,7 +467,21 @@ def get_user_upload_previews(
original_content_type=image_attachment.content_type,
transcoded_image=get_transcoded_format(image_attachment),
)
- return upload_preview_data
+
+ non_image_path_ids = [path_id for path_id in path_ids if image_metadata.get(path_id) is None]
+ non_image_attachments = Attachment.objects.filter(
+ realm_id=realm_id, path_id__in=non_image_path_ids
+ ).order_by("id")
+ audio_path_ids = {
+ attachment.path_id
+ for attachment in non_image_attachments
+ if attachment.content_type in AUDIO_INLINE_MIME_TYPES
+ }
+
+ return AttachmentData(
+ audio_path_ids=audio_path_ids,
+ image_metadata=image_metadata,
+ )
def get_default_thumbnail_url(image_attachment: ImageAttachment) -> tuple[str, bool]:
diff --git a/zerver/tests/fixtures/markdown_test_cases.json b/zerver/tests/fixtures/markdown_test_cases.json
index bb2ddb076bb..a956ce1b2c8 100644
--- a/zerver/tests/fixtures/markdown_test_cases.json
+++ b/zerver/tests/fixtures/markdown_test_cases.json
@@ -471,6 +471,12 @@
"backend_only_rendering": true,
"text_content": "Google link\n"
},
+ {
+ "name": "only_inline_audio_camo",
+ "input": "![Audio link](http://example.com/audio.mp3)",
+ "expected_output": "<p><audio controls data-original-url=\"http://example.com/audio.mp3\" preload=\"metadata\" src=\"https://external-content.zulipcdn.net/external_content/57cf2db553c3f6cc2af6781c11232e70983f4762/687474703a2f2f6578616d706c652e636f6d2f617564696f2e6d7033\" title=\"Audio link\"></audio></p>",
+ "backend_only_rendering": true
+ },
{
"name": "link_with_text",
"input": "[hello](https://github.com)",
diff --git a/zerver/tests/test_markdown.py b/zerver/tests/test_markdown.py
index 6d4f6a8636c..1209ce1f73a 100644
--- a/zerver/tests/test_markdown.py
+++ b/zerver/tests/test_markdown.py
@@ -69,6 +69,7 @@ from zerver.lib.streams import user_has_content_access, user_has_metadata_access
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.tex import render_tex
from zerver.lib.types import UserGroupMembersData
+from zerver.lib.upload import upload_message_attachment
from zerver.lib.user_groups import UserGroupMembershipDetails
from zerver.models import Message, NamedUserGroup, RealmEmoji, RealmFilter, UserMessage, UserProfile
from zerver.models.clients import get_client
@@ -766,6 +767,23 @@ class MarkdownLinkTest(ZulipTestCase):
class MarkdownEmbedsTest(ZulipTestCase):
+ def assert_message_content_is(
+ self, message_id: int, rendered_content: str, user_name: str = "othello"
+ ) -> None:
+ sender_user_profile = self.example_user(user_name)
+ result = self.assert_json_success(
+ self.api_get(sender_user_profile, f"/api/v1/messages/{message_id}")
+ )
+ self.assertEqual(result["message"]["content"], rendered_content)
+
+ def send_message_content(self, content: str, user_name: str = "othello") -> int:
+ sender_user_profile = self.example_user(user_name)
+ return self.send_stream_message(
+ sender=sender_user_profile,
+ stream_name="Verona",
+ content=content,
+ )
+
def test_inline_youtube(self) -> None:
msg = "Check out the debate: http://www.youtube.com/watch?v=hx1mjT73xYE"
converted = markdown_convert_wrapper(msg)
@@ -1005,6 +1023,46 @@ class MarkdownEmbedsTest(ZulipTestCase):
converted = render_message_markdown(msg, content)
self.assertEqual(converted.rendered_content, expected)
+ def test_inline_audio_preview(self) -> None:
+ # Test audio previews with a valid audio file upload.
+ url = upload_message_attachment(
+ "filename",
+ "audio/mpeg",
+ b"",
+ self.example_user("othello"),
+ )[0]
+ path_id = re.sub(r"/user_uploads/", "", url)
+ message_id = self.send_message_content(f"![Audio link](/user_uploads/{path_id})")
+ expected = (
+ f'<p><audio controls preload="metadata" src="{url}" title="Audio link"></audio></p>'
+ )
+ self.assert_message_content_is(message_id, expected)
+
+ # Test audio files are not previewed if the file doesn't
+ # exist.
+ url = "/user_uploads/path/to/file.mp3"
+ path_id = re.sub(r"/user_uploads/", "", url)
+
+ with self.assertLogs(level="WARNING"):
+ message_id = self.send_message_content(f"![Audio link](/user_uploads/{path_id})")
+
+ expected = f"<p>![Audio link]({url})</p>"
+ self.assert_message_content_is(message_id, expected)
+
+ # Test audio files are not previewed when the content type
+ # is not supported one, but filename contains a supported
+ # audio file extension.
+ url = upload_message_attachment(
+ "filename.mp3",
+ "",
+ b"",
+ self.example_user("othello"),
+ )[0]
+ path_id = re.sub(r"/user_uploads/", "", url)
+ message_id = self.send_message_content(f"![Audio link](/user_uploads/{path_id})")
+ expected = f"<p>![Audio link]({url})</p>"
+ self.assert_message_content_is(message_id, expected)
+
@override_settings(INLINE_IMAGE_PREVIEW=False)
def test_image_preview_enabled(self) -> None:
ret = image_preview_enabled()