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.

upload: Provide the frontend with the less-modified filename.

Alex Vandiver903bfb31e6de
diff --git a/version.py b/version.py
index 2c6584ae4a3..4670dc7f6d0 100644
--- a/version.py
+++ b/version.py
@@ -35,7 +35,7 @@ DESKTOP_WARNING_VERSION = "5.9.3"
# entries in the endpoint's documentation in `zulip.yaml`.
-API_FEATURE_LEVEL = 285 # Last bumped for detached_uploads
+API_FEATURE_LEVEL = 286 # Last bumped for uploaded filename
# 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/zerver/lib/email_mirror.py b/zerver/lib/email_mirror.py
index f28f7357406..16b608e4435 100644
--- a/zerver/lib/email_mirror.py
+++ b/zerver/lib/email_mirror.py
@@ -331,13 +331,17 @@ def extract_and_upload_attachments(message: EmailMessage, realm: Realm, sender:
if filename:
attachment = part.get_payload(decode=True)
if isinstance(attachment, bytes):
- upload_url = upload_message_attachment(
+ upload_url, filename = upload_message_attachment(
filename,
content_type,
attachment,
sender,
target_realm=realm,
)
+ # Our markdown has no escaping, so we cannot link any
+ # text containing brackets; strip them from the
+ # filename we're linking.
+ filename = re.sub(r"\[|\]", "", filename)
formatted_link = f"[{filename}]({upload_url})"
attachment_links.append(formatted_link)
else:
diff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.py
index 5cfcbbd9e6b..1f8c4b7ba19 100644
--- a/zerver/lib/test_classes.py
+++ b/zerver/lib/test_classes.py
@@ -2034,7 +2034,7 @@ Output:
attach_file.write(b"Hello, World!")
attach_file.flush()
with open(attach_file.name, "rb") as fp:
- file_path = upload_message_attachment_from_request(UploadedFile(fp), user)
+ file_path = upload_message_attachment_from_request(UploadedFile(fp), user)[0]
return file_path
diff --git a/zerver/lib/upload/__init__.py b/zerver/lib/upload/__init__.py
index 7724c7395aa..d108c8b428b 100644
--- a/zerver/lib/upload/__init__.py
+++ b/zerver/lib/upload/__init__.py
@@ -137,7 +137,7 @@ def upload_message_attachment(
file_data: bytes,
user_profile: UserProfile,
target_realm: Realm | None = None,
-) -> str:
+) -> tuple[str, str]:
if target_realm is None:
target_realm = user_profile.realm
path_id = upload_backend.generate_message_upload_path(
@@ -160,7 +160,7 @@ def upload_message_attachment(
user_profile,
target_realm,
)
- return f"/user_uploads/{path_id}"
+ return f"/user_uploads/{path_id}", uploaded_file_name
def claim_attachment(
@@ -187,7 +187,7 @@ def claim_attachment(
def upload_message_attachment_from_request(
user_file: UploadedFile, user_profile: UserProfile
-) -> str:
+) -> tuple[str, str]:
uploaded_file_name, content_type = get_file_info(user_file)
return upload_message_attachment(
uploaded_file_name, content_type, user_file.read(), user_profile
diff --git a/zerver/openapi/curl_param_value_generators.py b/zerver/openapi/curl_param_value_generators.py
index 7ea97e2133b..44047a1e926 100644
--- a/zerver/openapi/curl_param_value_generators.py
+++ b/zerver/openapi/curl_param_value_generators.py
@@ -352,7 +352,7 @@ def deactivate_own_user() -> dict[str, object]:
@openapi_param_value_generator(["/attachments/{attachment_id}:delete"])
def remove_attachment() -> dict[str, object]:
user_profile = helpers.example_user("iago")
- url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)
+ url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)[0]
attachment_id = url.replace("/user_uploads/", "").split("/")[0]
return {"attachment_id": attachment_id}
diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yaml
index a7a5939bc93..987fbbcf9f4 100644
--- a/zerver/openapi/zulip.yaml
+++ b/zerver/openapi/zulip.yaml
@@ -8250,6 +8250,12 @@ paths:
**Changes**: New in Zulip 9.0 (feature level 272). Previously,
this property was only available under the legacy `uri` name.
+ filename:
+ type: string
+ description: |
+ The filename that Zulip stored the upload as.
+
+ **Changes**: New in Zulip 10.0 (feature level 285).
example:
{
"msg": "",
diff --git a/zerver/tests/test_email_mirror.py b/zerver/tests/test_email_mirror.py
index f9c48e6c0cb..6600fb1090a 100644
--- a/zerver/tests/test_email_mirror.py
+++ b/zerver/tests/test_email_mirror.py
@@ -597,7 +597,7 @@ class TestEmailMirrorMessagesWithAttachments(ZulipTestCase):
with mock.patch(
"zerver.lib.email_mirror.upload_message_attachment",
- return_value="https://test_url",
+ return_value=("https://test_url", "image.png"),
) as upload_message_attachment:
process_message(incoming_valid_message)
upload_message_attachment.assert_called_with(
@@ -723,7 +723,7 @@ class TestEmailMirrorMessagesWithAttachments(ZulipTestCase):
with mock.patch(
"zerver.lib.email_mirror.upload_message_attachment",
- return_value="https://test_url",
+ return_value=("https://test_url", utf8_filename),
) as upload_message_attachment:
process_message(incoming_valid_message)
upload_message_attachment.assert_called_with(
@@ -769,7 +769,7 @@ class TestEmailMirrorMessagesWithAttachments(ZulipTestCase):
with mock.patch(
"zerver.lib.email_mirror.upload_message_attachment",
- return_value="https://test_url",
+ return_value=("https://test_url", "image.png"),
) as upload_message_attachment:
process_message(incoming_valid_message)
upload_message_attachment.assert_called_with(
diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.py
index 9e0480b47e1..07527128261 100644
--- a/zerver/tests/test_events.py
+++ b/zerver/tests/test_events.py
@@ -1037,7 +1037,7 @@ class NormalActionsTest(BaseAction):
iago = self.example_user("iago")
url = upload_message_attachment(
"img.png", "image/png", read_test_image_file("img.png"), self.example_user("iago")
- )
+ )[0]
path_id = url[len("/user_upload/") + 1 :]
self.send_stream_message(
iago, "Verona", f"[img.png]({url})", skip_capture_on_commit_callbacks=True
diff --git a/zerver/tests/test_import_export.py b/zerver/tests/test_import_export.py
index 4be76c0bf14..63fb9512a15 100644
--- a/zerver/tests/test_import_export.py
+++ b/zerver/tests/test_import_export.py
@@ -168,7 +168,7 @@ class ExportFile(ZulipTestCase):
self, user_profile: UserProfile, *, emoji_name: str = "whatever"
) -> None:
message = most_recent_message(user_profile)
- url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)
+ url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)[0]
attachment_path_id = url.replace("/user_uploads/", "")
claim_attachment(
path_id=attachment_path_id,
@@ -402,7 +402,7 @@ class RealmImportExportTest(ExportFile):
# We create an attachment tied to a personal message. That means it shouldn't be
# included in a public export, as it's private data.
personal_message_id = self.send_personal_message(user_profile, self.example_user("othello"))
- url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)
+ url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)[0]
attachment_path_id = url.replace("/user_uploads/", "")
attachment = claim_attachment(
path_id=attachment_path_id,
diff --git a/zerver/tests/test_markdown_thumbnail.py b/zerver/tests/test_markdown_thumbnail.py
index c426becdb61..1ebea1654b4 100644
--- a/zerver/tests/test_markdown_thumbnail.py
+++ b/zerver/tests/test_markdown_thumbnail.py
@@ -145,7 +145,7 @@ class MarkdownThumbnailTest(ZulipTestCase):
"image/png",
read_test_image_file("img.png"),
self.example_user("othello"),
- )
+ )[0]
path_id = re.sub(r"/user_uploads/", "", url)
self.assertTrue(ImageAttachment.objects.filter(path_id=path_id).exists())
message_id = self.send_message_content(f"[I am 95% ± 5% certain!](/user_uploads/{path_id})")
diff --git a/zerver/tests/test_realm.py b/zerver/tests/test_realm.py
index d7c5b890680..ad3125fd096 100644
--- a/zerver/tests/test_realm.py
+++ b/zerver/tests/test_realm.py
@@ -2468,7 +2468,7 @@ class ScrubRealmTest(ZulipTestCase):
path_ids = []
for n in range(1, 4):
content = f"content{n}".encode()
- url = upload_message_attachment(f"dummy{n}.txt", "text/plain", content, hamlet)
+ url = upload_message_attachment(f"dummy{n}.txt", "text/plain", content, hamlet)[0]
base = "/user_uploads/"
self.assertEqual(base, url[: len(base)])
path_id = re.sub(r"/user_uploads/", "", url)
@@ -2543,7 +2543,7 @@ class ScrubRealmTest(ZulipTestCase):
file_paths = []
for n, owner in enumerate([iago, othello, hamlet, cordelia, king]):
content = f"content{n}".encode()
- url = upload_message_attachment(f"dummy{n}.txt", "text/plain", content, owner)
+ url = upload_message_attachment(f"dummy{n}.txt", "text/plain", content, owner)[0]
base = "/user_uploads/"
self.assertEqual(base, url[: len(base)])
file_path = os.path.join(settings.LOCAL_FILES_DIR, re.sub(r"/user_uploads/", "", url))
diff --git a/zerver/tests/test_upload.py b/zerver/tests/test_upload.py
index 1a498af12db..7e9bc587f34 100644
--- a/zerver/tests/test_upload.py
+++ b/zerver/tests/test_upload.py
@@ -613,14 +613,15 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase):
def test_sanitize_file_name(self) -> None:
self.login("hamlet")
- for uploaded_filename, expected in [
- ("../foo", "foo"),
- (".. ", "uploaded-file"),
- ("/", "f1"),
- ("./", "f1"),
- ("././", "f1"),
- (".!", "uploaded-file"),
- ("**", "uploaded-file"),
+ for uploaded_filename, expected_url, expected_filename in [
+ ("../foo", "foo", "foo"),
+ (".. ", "uploaded-file", ".. "),
+ ("/", "f1", "f1"),
+ ("./", "f1", "f1"),
+ ("././", "f1", "f1"),
+ (".!", "uploaded-file", ".!"),
+ ("**", "uploaded-file", "**"),
+ ("foo bar--baz", "foo-bar-baz", "foo bar--baz"),
]:
fp = StringIO("bah!")
fp.name = quote(uploaded_filename)
@@ -628,9 +629,10 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase):
result = self.client_post("/json/user_uploads", {"f1": fp})
response_dict = self.assert_json_success(result)
self.assertNotIn(response_dict["uri"], uploaded_filename)
- self.assertTrue(response_dict["uri"].endswith("/" + expected))
+ self.assertTrue(response_dict["uri"].endswith("/" + expected_url))
self.assertNotIn(response_dict["url"], uploaded_filename)
- self.assertTrue(response_dict["url"].endswith("/" + expected))
+ self.assertTrue(response_dict["url"].endswith("/" + expected_url))
+ self.assertEqual(response_dict["filename"], expected_filename)
def test_realm_quota(self) -> None:
"""
diff --git a/zerver/tests/test_upload_local.py b/zerver/tests/test_upload_local.py
index a02c852a813..85cabc57f8e 100644
--- a/zerver/tests/test_upload_local.py
+++ b/zerver/tests/test_upload_local.py
@@ -30,7 +30,7 @@ from zerver.models.users import get_system_bot
class LocalStorageTest(UploadSerializeMixin, ZulipTestCase):
def test_upload_message_attachment(self) -> None:
user_profile = self.example_user("hamlet")
- url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)
+ url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)[0]
base = "/user_uploads/"
self.assertEqual(base, url[: len(base)])
@@ -45,7 +45,7 @@ class LocalStorageTest(UploadSerializeMixin, ZulipTestCase):
def test_save_attachment_contents(self) -> None:
user_profile = self.example_user("hamlet")
- url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)
+ url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)[0]
path_id = re.sub(r"/user_uploads/", "", url)
output = BytesIO()
@@ -65,7 +65,7 @@ class LocalStorageTest(UploadSerializeMixin, ZulipTestCase):
url = upload_message_attachment(
"dummy.txt", "text/plain", b"zulip!", user_profile, zulip_realm
- )
+ )[0]
# Ensure the correct realm id of the target realm is used instead of the bot's realm.
self.assertTrue(url.startswith(f"/user_uploads/{zulip_realm.id}/"))
@@ -93,7 +93,7 @@ class LocalStorageTest(UploadSerializeMixin, ZulipTestCase):
user_profile = self.example_user("hamlet")
path_ids = []
for n in range(1, 1005):
- url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)
+ url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)[0]
base = "/user_uploads/"
self.assertEqual(base, url[: len(base)])
path_id = re.sub(r"/user_uploads/", "", url)
diff --git a/zerver/tests/test_upload_s3.py b/zerver/tests/test_upload_s3.py
index e79df66f639..98a9d7685d6 100644
--- a/zerver/tests/test_upload_s3.py
+++ b/zerver/tests/test_upload_s3.py
@@ -49,7 +49,7 @@ class S3Test(ZulipTestCase):
bucket = create_s3_buckets(settings.S3_AUTH_UPLOADS_BUCKET)[0]
user_profile = self.example_user("hamlet")
- url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)
+ url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)[0]
base = "/user_uploads/"
self.assertEqual(base, url[: len(base)])
@@ -68,7 +68,7 @@ class S3Test(ZulipTestCase):
def test_save_attachment_contents(self) -> None:
create_s3_buckets(settings.S3_AUTH_UPLOADS_BUCKET)
user_profile = self.example_user("hamlet")
- url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)
+ url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)[0]
path_id = re.sub(r"/user_uploads/", "", url)
output = BytesIO()
@@ -90,7 +90,7 @@ class S3Test(ZulipTestCase):
url = upload_message_attachment(
"dummy.txt", "text/plain", b"zulip!", user_profile, zulip_realm
- )
+ )[0]
# Ensure the correct realm id of the target realm is used instead of the bot's realm.
self.assertTrue(url.startswith(f"/user_uploads/{zulip_realm.id}/"))
@@ -99,7 +99,7 @@ class S3Test(ZulipTestCase):
bucket = create_s3_buckets(settings.S3_AUTH_UPLOADS_BUCKET)[0]
user_profile = self.example_user("hamlet")
- url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)
+ url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)[0]
path_id = re.sub(r"/user_uploads/", "", url)
self.assertIsNotNone(bucket.Object(path_id).get())
@@ -114,7 +114,7 @@ class S3Test(ZulipTestCase):
user_profile = self.example_user("hamlet")
path_ids = []
for n in range(1, 5):
- url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)
+ url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)[0]
path_id = re.sub(r"/user_uploads/", "", url)
self.assertIsNotNone(bucket.Object(path_id).get())
path_ids.append(path_id)
@@ -147,14 +147,14 @@ class S3Test(ZulipTestCase):
user_profile = self.example_user("hamlet")
path_ids = []
for n in range(1, 5):
- url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)
+ url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)[0]
path_ids.append(re.sub(r"/user_uploads/", "", url))
# Put an image in, which gets thumbnailed
with self.captureOnCommitCallbacks(execute=True):
url = upload_message_attachment(
"img.png", "image/png", read_test_image_file("img.png"), user_profile
- )
+ )[0]
image_path_id = re.sub(r"/user_uploads/", "", url)
path_ids.append(image_path_id)
diff --git a/zerver/views/upload.py b/zerver/views/upload.py
index 6eb6044210b..c475ac5608f 100644
--- a/zerver/views/upload.py
+++ b/zerver/views/upload.py
@@ -440,8 +440,8 @@ def upload_file_backend(request: HttpRequest, user_profile: UserProfile) -> Http
)
check_upload_within_quota(user_profile.realm, file_size)
- url = upload_message_attachment_from_request(user_file, user_profile)
+ url, filename = upload_message_attachment_from_request(user_file, user_profile)
# TODO/compatibility: uri is a deprecated alias for url that can
# be removed once there are no longer clients relying on it.
- return json_success(request, data={"uri": url, "url": url})
+ return json_success(request, data={"uri": url, "url": url, "filename": filename})