Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
data_import: Refactor how Slack emoji is processed.
PieterCK89c0925d8c09
diff --git a/zerver/data_import/import_util.py b/zerver/data_import/import_util.pyindex 17fc1b3d0ff..d40f29f0fe8 100644--- a/zerver/data_import/import_util.py+++ b/zerver/data_import/import_util.py@@ -19,9 +19,10 @@ from django.utils.timezone import now as timezone_nowfrom zerver.data_import.sequencer import NEXT_IDfrom zerver.lib.avatar_hash import user_avatar_base_path_from_ids+from zerver.lib.emoji import get_emoji_file_namefrom zerver.lib.markdown import get_markdown_link_for_urlfrom zerver.lib.message import normalize_body_for_import-from zerver.lib.mime_types import INLINE_MIME_TYPES, bare_content_type, guess_extension+from zerver.lib.mime_types import INLINE_MIME_TYPES, bare_content_type, guess_typefrom zerver.lib.parallel import run_parallelfrom zerver.lib.partial import partialfrom zerver.lib.stream_color import STREAM_ASSIGNMENT_COLORS as STREAM_COLORS@@ -50,6 +51,12 @@ class AttachmentLinkResult:markdown_link: str+@dataclass+class GetEmojiResult:+ path_id: str+ filename: str++DATA_IMPORT_CLIENTS = {# Match low ID clients in zerver/lib/server_initialization.py.# This has no functional impact other than ensuring low IDs.@@ -727,7 +734,40 @@ def build_realm_emoji(realm_id: int, name: str, id: int, file_name: str) -> Zerv)-def get_emojis(emoji_dir: str, emoji_url: str, emoji_path: str) -> str | None:+def get_emojis(+ emoji_dir: str,+ emoji_url: str,+ emoji_name: str,+ emoji_id: int,+ realm_id: int,+) -> GetEmojiResult:+ """+ This downloads the given `emoji_url` into the given `emoji_dir`.++ Raises `BadImageError` when the content-type is not guessable, or+ not in both `THUMBNAIL_ACCEPT_IMAGE_TYPES` and `INLINE_MIME_TYPES`.+ """+ response = requests.get(emoji_url, stream=True)+ content_type_raw = response.headers.get("Content-Type")+ if content_type_raw is None:+ logging.warning(+ "Emoji %s has an unspecified content type. Guessing from the file extension of %s",+ emoji_name,+ emoji_url,+ )+ type, encoding = guess_type(emoji_url)+ if type is None or encoding is not None:+ raise BadImageError(f"Unknown content type for: {emoji_name}")+ content_type_raw = type+ content_type = bare_content_type(content_type_raw)+ if content_type not in THUMBNAIL_ACCEPT_IMAGE_TYPES or content_type not in INLINE_MIME_TYPES:+ raise BadImageError(+ f"Emoji {emoji_name} is not an image file. Content type: {content_type}"+ )+ emoji_file_name = get_emoji_file_name(content_type, emoji_id)+ emoji_path = RealmEmoji.PATH_ID_TEMPLATE.format(+ realm_id=realm_id, emoji_file_name=emoji_file_name+ )upload_emoji_path = os.path.join(emoji_dir, emoji_path)response = request_file_stream(emoji_url)@@ -735,7 +775,7 @@ def get_emojis(emoji_dir: str, emoji_url: str, emoji_path: str) -> str | None:with open(upload_emoji_path, "wb") as emoji_file:shutil.copyfileobj(response.raw, emoji_file)- return response.headers.get("Content-Type")+ return GetEmojiResult(path_id=emoji_path, filename=emoji_file_name)def process_emojis(@@ -757,46 +797,25 @@ def process_emojis(logging.info("DOWNLOADING EMOJIS .......\n")for emoji in zerver_realmemoji:emoji_url = emoji_url_map[emoji["name"]]- emoji_path = RealmEmoji.PATH_ID_TEMPLATE.format(- realm_id=emoji["realm"], emoji_file_name=emoji["name"]++ emoji_result = get_emojis(+ emoji_dir,+ emoji_url,+ emoji["name"],+ emoji["id"],+ emoji["realm"],)emoji_record = dict(emoji)- emoji_record["path"] = emoji_path- emoji_record["s3_path"] = emoji_path+ emoji_record["path"] = emoji_result.path_id+ emoji_record["s3_path"] = emoji_result.path_idemoji_record["realm_id"] = emoji_record["realm"]+ emoji_record["file_name"] = emoji_result.filenameemoji_record.pop("realm")emoji_records.append(emoji_record)- # Directly download the emoji and patch the file_name with the correct extension- # based on the content-type returned by the server. This is needed because Slack- # sometimes returns an emoji url with .png extension despite the file being a gif.- content_type_raw = get_emojis(emoji_dir, emoji_url, emoji_path)- if content_type_raw is None:- logging.warning(- "Emoji %s has an unspecified content type. Using the original file extension.",- emoji["name"],- )- continue-- content_type = bare_content_type(content_type_raw)- if (- content_type not in THUMBNAIL_ACCEPT_IMAGE_TYPES- or content_type not in INLINE_MIME_TYPES- ):- raise BadImageError(- f"Emoji {emoji['name']} is not an image file. Content type: {content_type}"- )-- file_extension = guess_extension(content_type, strict=False)- assert file_extension is not None-- old_file_name = emoji_record["file_name"]- new_file_name = f"{old_file_name.rsplit('.', 1)[0]}{file_extension}"-- emoji_record["file_name"] = new_file_name- emoji["file_name"] = new_file_name+ emoji["file_name"] = emoji_result.filenamelogging.info("######### GETTING EMOJIS FINISHED #########\n")return emoji_recordsdiff --git a/zerver/data_import/slack.py b/zerver/data_import/slack.pyindex 2ef7598e625..187ca6e722a 100644--- a/zerver/data_import/slack.py+++ b/zerver/data_import/slack.py@@ -1,7 +1,6 @@import itertoolsimport loggingimport os-import posixpathimport reimport shutilimport time@@ -54,7 +53,7 @@ from zerver.data_import.slack_message_conversion import (get_user_full_name,process_slack_block_and_attachment,)-from zerver.lib.emoji import codepoint_to_name, get_emoji_file_name+from zerver.lib.emoji import codepoint_to_namefrom zerver.lib.exceptions import SlackImportInvalidFileErrorfrom zerver.lib.export import MESSAGE_BATCH_CHUNK_SIZE, do_common_export_processesfrom zerver.lib.message import truncate_content@@ -248,14 +247,10 @@ def build_realmemoji(for emoji_name, url in custom_emoji_list.items():split_url = urlsplit(url)if split_url.hostname == "emoji.slack-edge.com":- # Some of the emojis we get from the API have invalid links- # this is to prevent errors related to them- content_type = guess_type(posixpath.basename(split_url.path))[0]- assert content_type is not Nonerealmemoji = RealmEmoji(name=emoji_name,id=emoji_id,- file_name=get_emoji_file_name(content_type, emoji_id),+ file_name=None,deactivated=False,)diff --git a/zerver/tests/test_slack_importer.py b/zerver/tests/test_slack_importer.pyindex 06135d44be9..4cbe2301521 100644--- a/zerver/tests/test_slack_importer.py+++ b/zerver/tests/test_slack_importer.py@@ -1,6 +1,7 @@import osimport reimport shutil+import tempfilefrom collections.abc import Iteratorfrom io import BytesIOfrom typing import TYPE_CHECKING, Any@@ -10,6 +11,7 @@ from urllib.parse import parse_qs, urlsplitimport orjsonimport responses+from attr import dataclassfrom django.conf import settingsfrom django.http import HttpResponsefrom django.test import override_settings@@ -31,6 +33,7 @@ from zerver.data_import.import_util import (build_usermessages,build_zerver_realm,download_and_export_upload_file,+ get_emojis,)from zerver.data_import.sequencer import NEXT_IDfrom zerver.data_import.slack import (@@ -62,8 +65,10 @@ from zerver.data_import.slack import ()from zerver.lib.exceptions import SlackImportInvalidFileErrorfrom zerver.lib.import_realm import do_import_realm+from zerver.lib.mime_types import INLINE_MIME_TYPESfrom zerver.lib.test_classes import ZulipTestCasefrom zerver.lib.test_helpers import find_key_by_email, read_test_image_file+from zerver.lib.thumbnail import THUMBNAIL_ACCEPT_IMAGE_TYPES, BadImageErrorfrom zerver.lib.topic import EXPORT_TOPIC_NAMEfrom zerver.models import (Message,@@ -3111,3 +3116,170 @@ by Pieterlogs.output,)self.assertEqual("Failed downloading file.", str(e.exception))++ @responses.activate+ def test_slack_get_emojis(self) -> None:+ @dataclass+ class FileFixture:+ content_type: str+ file_type_extension: str+ url: str++ file_fixtures = [+ FileFixture(+ content_type="image/png",+ file_type_extension=".png",+ url="https://emoji.slack-edge.com/T06NRA6HM3P/bowtie/f3ec6f2bb0.png",+ ),+ FileFixture(+ content_type="image/gif",+ file_type_extension=".gif",+ url="https://emoji.slack-edge.com/T06NRA6HM3P/bowtie/f3ec6f2bb0.gif",+ ),+ ]+ realm_id = 0+ output_dir = tempfile.mkdtemp()+ emoji_name = "bow_tie"++ for file_fixture in file_fixtures:+ with self.subTest(content_type=file_fixture.content_type):+ responses.add(+ responses.GET,+ file_fixture.url,+ body=read_test_image_file("img.png"),+ content_type=file_fixture.content_type,+ status=200,+ )++ try:+ emoji_result = get_emojis(+ output_dir,+ file_fixture.url,+ emoji_name,+ 10,+ realm_id,+ )++ assert emoji_result.filename is not None+ self.assertFalse(emoji_result.filename.startswith(emoji_name))+ self.assertRegex(emoji_result.filename, r"^[a-f0-9]{8}\.\w+$")+ self.assertTrue(+ emoji_result.filename.endswith(file_fixture.file_type_extension)+ )+ emoji_dir = os.path.join(output_dir, str(realm_id), "emoji", "images")+ emoji_files = os.listdir(emoji_dir)+ self.assert_length(emoji_files, 1)+ finally:+ shutil.rmtree(output_dir)++ @responses.activate+ def test_slack_get_emojis_unknown_content_type(self) -> None:+ realm_id = 0+ output_dir = tempfile.mkdtemp()+ emoji_name = "bow_tie"+ emoji_url = "https://emoji.slack-edge.com/T06NRA6HM3P/bowtie/f3ec6f2bb0.png"+ unknown_image_type = "image/unknown"++ self.assertTrue(+ unknown_image_type not in THUMBNAIL_ACCEPT_IMAGE_TYPES+ or unknown_image_type not in INLINE_MIME_TYPES+ )++ responses.add(+ responses.GET,+ emoji_url,+ body=read_test_image_file("img.png"),+ content_type=unknown_image_type,+ status=200,+ )++ with self.assertRaises(BadImageError) as e:+ get_emojis(+ output_dir,+ emoji_url,+ emoji_name,+ 10,+ realm_id,+ )+ self.assertEqual(+ f"Emoji {emoji_name} is not an image file. Content type: {unknown_image_type}",+ str(e.exception),+ )+ emoji_dir = os.path.join(output_dir, str(realm_id), "emoji", "images")+ self.assertFalse(os.path.exists(emoji_dir))++ @responses.activate+ def test_guess_emoji_content_type(self) -> None:+ realm_id = 0+ output_dir = tempfile.mkdtemp()+ emoji_name = "unknown_content_type"+ emoji_url = "https://emoji.slack-edge.com/T06NRA6HM3P/slack_zulip/3d93d672c2ba4dfc.gif"++ responses.add(+ responses.GET,+ emoji_url,+ body=read_test_image_file("img.png"),+ content_type=None,+ status=200,+ )++ try:+ with self.assertLogs(level="WARN") as logs:+ emoji_result = get_emojis(+ output_dir,+ emoji_url,+ emoji_name,+ 10,+ realm_id,+ )++ self.assertIn(+ f"WARNING:root:Emoji {emoji_name} has an unspecified content type. Guessing from the file extension of {emoji_url}",+ logs.output,+ )++ assert emoji_result.filename is not None+ self.assertFalse(emoji_result.filename.startswith(emoji_name))+ self.assertRegex(emoji_result.filename, r"^[a-f0-9]{8}\.\w+$")+ self.assertTrue(emoji_result.filename.endswith(".gif"))+ emoji_dir = os.path.join(output_dir, str(realm_id), "emoji", "images")+ emoji_files = os.listdir(emoji_dir)+ self.assert_length(emoji_files, 1)+ finally:+ shutil.rmtree(output_dir)++ @responses.activate+ def test_failed_to_guess_emoji_content_type(self) -> None:+ realm_id = 0+ output_dir = tempfile.mkdtemp()+ emoji_name = "unknown_content_type_and_not_guessable"+ emoji_url = "https://emoji.slack-edge.com/T06NRA6HM3P/bowtie/f3ec6f2bb0.unknown"++ responses.add(+ responses.GET,+ emoji_url,+ body=read_test_image_file("img.png"),+ content_type=None,+ status=200,+ )++ with self.assertLogs(level="WARN") as logs, self.assertRaises(BadImageError) as e:+ get_emojis(+ output_dir,+ emoji_url,+ emoji_name,+ 10,+ realm_id,+ )++ self.assertIn(+ f"WARNING:root:Emoji {emoji_name} has an unspecified content type. Guessing from the file extension of {emoji_url}",+ logs.output,+ )++ self.assertIn(+ f"Unknown content type for: {emoji_name}",+ str(e.exception),+ )+ emoji_dir = os.path.join(output_dir, str(realm_id), "emoji", "images")+ self.assertFalse(os.path.exists(emoji_dir))