Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
ms_teams_importer: Convert hosted content message attachments.
PieterCKa2235c50cbb2
diff --git a/starlight_help/src/content/docs/import-from-microsoft-teams.mdx b/starlight_help/src/content/docs/import-from-microsoft-teams.mdxindex a6c52d8bf33..c04ab482897 100644--- a/starlight_help/src/content/docs/import-from-microsoft-teams.mdx+++ b/starlight_help/src/content/docs/import-from-microsoft-teams.mdx@@ -81,9 +81,12 @@ APIs](https://learn.microsoft.com/en-us/microsoftteams/migration-from-teams#step### Authorize a Microsoft Graph API token-Some organization data are not exported by the Teams data export tool. The Zulip import+Some organization data is not exported by the Teams data export tool. The Zulip importtool will call several Microsoft Graph APIs to collect the following data:+* [**Hosted contents**](https://learn.microsoft.com/en-us/graph/api/resources/chatmessagehostedcontent?view=graph-rest-1.0).+ Teams content hosted in a chat message, such as images or code snippets.+* **User roles**. The [user roles](#user-roles) section explains how MicrosoftTeams users roles and user types are mapped to Zulip user roles.@@ -107,6 +110,7 @@ token](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-clien1. Select **Application permissions** as the permission type.1. Search and add these permissions:+ * `ChannelMessage.Read.All`* `User.Read.All`* `RoleManagement.Read.Directory`@@ -164,6 +168,7 @@ tool:| [directory role list member](https://learn.microsoft.com/en-us/graph/api/directoryrole-list-members?view=graph-rest-1.0\&tabs=http) | Used to find users who are global administrators. | `User.Read.All` || [list directory role](https://learn.microsoft.com/en-us/graph/api/directoryrole-list?view=graph-rest-1.0\&tabs=http) | Used to find the ID for the global administrator role. | `RoleManagement.Read.Directory` || [list user](https://learn.microsoft.com/en-us/graph/api/user-list?view=graph-rest-1.0\&tabs=http) | Used to find guest accounts. | `User.Read.All` |+| [get hosted content](https://learn.microsoft.com/en-us/graph/api/chatmessagehostedcontent-get?view=graph-rest-1.0\&tabs=http) | Used to download hosted content attachments. | `ChannelMessage.Read.All` |### Import your data into Zulip@@ -217,7 +222,7 @@ can be extended to include it.* Direct messages and messages in private channels* Meeting chats and recordings-* Message attachments+* Message attachments stored in Microsoft SharePoint are not imported.* Message reactions* Message edit history, and system messages such as `@user_a added @user_b to the chat`* Custom emojidiff --git a/tools/linter_lib/custom_check.py b/tools/linter_lib/custom_check.pyindex 1ace6f34197..bca60e9fd1b 100644--- a/tools/linter_lib/custom_check.py+++ b/tools/linter_lib/custom_check.py@@ -903,7 +903,7 @@ help_markdown_rules = RuleList("pattern": "[a-z][.][A-Z]","description": "Likely missing space after end of sentence","include_only": {"starlight_help/src/content/docs/"},- "exclude_pattern": "Rocket.Chat|org.zulip.Zulip|Directory.Read.All|RoleManagement.Read.Directory|User.Read.All",+ "exclude_pattern": "Rocket.Chat|org.zulip.Zulip|Directory.Read.All|RoleManagement.Read.Directory|User.Read.All|ChannelMessage.Read.All",},{"pattern": r"\b[rR]ealm[s]?\b",diff --git a/zerver/data_import/import_util.py b/zerver/data_import/import_util.pyindex 0b45d53f88d..0d6c5a7ce4c 100644--- a/zerver/data_import/import_util.py+++ b/zerver/data_import/import_util.py@@ -566,6 +566,22 @@ def build_message(return zulip_message_dict+# Keep this in sync with the Attachment table.+@dataclass+class AttachmentRecordData:+ content_type: str+ create_time: float+ file_name: str+ id: int+ is_realm_public: bool+ messages: list[int]+ owner: int+ path_id: str+ realm: int+ scheduled_messages: list[int]+ size: int++def build_attachment(realm_id: int,message_ids: set[int],diff --git a/zerver/data_import/microsoft_teams.py b/zerver/data_import/microsoft_teams.pyindex 2541815b4e8..859899540bc 100644--- a/zerver/data_import/microsoft_teams.py+++ b/zerver/data_import/microsoft_teams.py@@ -1,18 +1,24 @@import loggingimport os+import re+import shutilfrom collections import defaultdict-from collections.abc import Iterable+from collections.abc import Callable, Iterablefrom dataclasses import dataclassfrom datetime import datetimefrom email.headerregistry import Addressfrom typing import Any, Literal, TypeAliasfrom urllib.parse import SplitResult+import regeximport requestsfrom django.conf import settingsfrom django.utils.timezone import now as timezone_nowfrom zerver.data_import.import_util import (+ AttachmentRecordData,+ UploadFileRequest,+ UploadRecordData,ZerverFieldsT,build_message,build_realm,@@ -24,12 +30,18 @@ from zerver.data_import.import_util import (build_zerver_realm,convert_html_to_text,create_converted_data_files,+ get_attachment_path_and_content,get_data_file,make_subscriber_map,+ request_file_stream,validate_user_emails_for_import,)from zerver.data_import.sequencer import NEXT_IDfrom zerver.lib.export import MESSAGE_BATCH_CHUNK_SIZE, do_common_export_processes+from zerver.lib.markdown import get_markdown_link_for_url+from zerver.lib.mime_types import bare_content_type+from zerver.lib.parallel import run_parallel_queue+from zerver.lib.partial import partialfrom zerver.models.recipients import Recipientfrom zerver.models.users import UserProfile@@ -66,6 +78,21 @@ class ChannelMetadata:class MessageConversionResult:zerver_messages: list[ZerverFieldsT]zerver_usermessages: list[ZerverFieldsT]+ upload_records: list[UploadRecordData]+++@dataclass+class AttachmentConversionResult:+ updated_content: str+ upload_records: list[UploadRecordData]+++@dataclass+class ExportMessageAttachmentParameter:+ realm_id: int+ message_id: int+ sender_id: int+ upload_file_request: UploadFileRequestAddedTeamsT: TypeAlias = dict[str, TeamMetadata]@@ -181,6 +208,16 @@ class ODataQueryParameter:MICROSOFT_GRAPH_API_URL = "https://graph.microsoft.com/v1.0{endpoint}"+# https://learn.microsoft.com/en-us/graph/api/chatmessagehostedcontent-get+HOSTED_CONTENT_GRAPH_API_URL_REGEX = r"https://graph\.microsoft\.com/v1\.0/teams/[^/]+/channels/[^/]+/messages/[^/]+/hostedContents/[^/]+/\$value"+HOSTED_CONTENT_FILE_REGEX = rf"""+ \[+ (?P<file_name>[^\]]+)+ \]\(+ (?P<api_url>{HOSTED_CONTENT_GRAPH_API_URL_REGEX})+ \)+ """+def get_microsoft_graph_api_data(api_url: str,@@ -400,11 +437,141 @@ def is_microsoft_teams_event_message(message: MicrosoftTeamsFieldsT) -> bool:return message["MessageType"] == "unknownFutureValue" and message["From"] is None+def download_and_export_microsoft_teams_upload_file(+ attachment_records: list[AttachmentRecordData],+ output_dir: str,+ args: ExportMessageAttachmentParameter,+) -> None:+ upload_file_request = args.upload_file_request+ response = request_file_stream(+ upload_file_request.request_url,+ upload_file_request.params,+ upload_file_request.headers,+ **upload_file_request.kwargs,+ )++ # Don't add the file type extension here. The file path will be remapped+ # during import and must match the updated URL in the message content.+ # The actual file's content type will be included in its attachment+ # record.+ file_output_path = os.path.join(+ output_dir, "uploads", f"{upload_file_request.output_file_path_id}"+ )++ os.makedirs(os.path.dirname(file_output_path), exist_ok=True)+ with open(file_output_path, "wb") as upload_file:+ shutil.copyfileobj(response.raw, upload_file)++ raw_content_type = response.headers.get("Content-Type")+ assert raw_content_type is not None++ # Can't use build_attachment here since Django doesn't support parallel+ # connection to the db.+ attachment_records.append(+ AttachmentRecordData(+ content_type=bare_content_type(raw_content_type),+ create_time=os.path.getmtime(file_output_path),+ file_name=os.path.basename(file_output_path),+ id=NEXT_ID("attachment"),+ is_realm_public=True,+ messages=[args.message_id],+ owner=args.sender_id,+ path_id=upload_file_request.output_file_path_id,+ realm=args.realm_id,+ scheduled_messages=[],+ size=os.path.getsize(file_output_path),+ )+ )+++def process_hosted_content_attachments(+ content: str,+ do_download_and_export_upload_file: Callable[[ExportMessageAttachmentParameter], None],+ is_direct_message_type: bool,+ microsoft_graph_api_token: str,+ realm_id: int,+ teams_message_id: str,+ zulip_message_id: int,+ zulip_user_id: int,+) -> AttachmentConversionResult:+ """+ "Hosted contents" are message file attachments that can be fetched straight+ from Microsoft Graph API. As of April 2026, there are only 3 known types of+ items that are categorized as "hosted contents":+ * images+ * custom emojis+ * code snippets++ Since custom emoji and code snippet are formatted as custom HTML blocks,+ convert_html_to_text will turn them into empty strings, so this currently+ only supports processing image hosted contents.++ It's worth checking the API documentation for the hosted content once in a+ while to verify what file types "hosted content" includes, since the code path+ for this relies on that being only images:+ https://learn.microsoft.com/en-us/graph/api/chatmessagehostedcontent-get+ """+ upload_records: list[UploadRecordData] = []++ def export_file_and_get_zulip_url(match: regex.Match[str]) -> str:+ file_name = match.group("file_name")+ hosted_content_api_url = match.group("api_url")+ attachment_data = get_attachment_path_and_content(file_name, teams_message_id, realm_id)++ upload_records.append(+ UploadRecordData(+ content_type=None,+ last_modified=float(timezone_now().timestamp()),+ path=attachment_data.path_id,+ realm_id=realm_id,+ s3_path=attachment_data.path_id,+ size=0,+ user_profile_id=zulip_user_id,+ )+ )++ do_download_and_export_upload_file(+ ExportMessageAttachmentParameter(+ realm_id=realm_id,+ message_id=zulip_message_id,+ sender_id=zulip_user_id,+ upload_file_request=UploadFileRequest(+ output_file_path_id=attachment_data.path_id,+ request_url=hosted_content_api_url,+ params=None,+ headers={"Authorization": f"Bearer {microsoft_graph_api_token}"},+ kwargs={},+ ),+ )+ )+ # Use inline thumbnail here since MS Teams only supports customizing the hosted+ # content image's alt tag.+ return get_markdown_link_for_url(file_name, attachment_data.url, inline_thumbnail=True)++ if is_direct_message_type:+ # TODO: hosted content URL for private chats have a different format, we+ # can process it once we support converting direct messages.+ return AttachmentConversionResult(updated_content=content, upload_records=upload_records)+ else:+ updated_content = regex.sub(+ HOSTED_CONTENT_FILE_REGEX,+ export_file_and_get_zulip_url,+ content,+ flags=re.VERBOSE,+ )+ return AttachmentConversionResult(+ updated_content=updated_content,+ upload_records=upload_records,+ )++def process_messages(added_teams: dict[str, TeamMetadata],channel_metadata: None | dict[str, ChannelMetadata],+ do_download_and_export_upload_file: Callable[[ExportMessageAttachmentParameter], None],domain_name: str,messages: list[MicrosoftTeamsFieldsT],+ microsoft_graph_api_token: str,microsoft_teams_user_id_to_zulip_user_id: MicrosoftTeamsUserIdToZulipUserIdT,realm: dict[str, Any],realm_id: int,@@ -412,6 +579,7 @@ def process_messages() -> MessageConversionResult:zerver_usermessage: list[ZerverFieldsT] = []zerver_messages: list[ZerverFieldsT] = []+ accumulated_batch_upload_records: list[UploadRecordData] = []for message in messages:if is_microsoft_teams_event_message(message):@@ -462,20 +630,44 @@ def process_messages()message_id = NEXT_ID("message")+ user_id = microsoft_teams_user_id_to_zulip_user_id[microsoft_teams_sender_id]+ attachment_result = process_hosted_content_attachments(+ content=content,+ do_download_and_export_upload_file=do_download_and_export_upload_file,+ is_direct_message_type=is_direct_message_type,+ microsoft_graph_api_token=microsoft_graph_api_token,+ realm_id=realm_id,+ teams_message_id=message["Id"],+ zulip_user_id=user_id,+ zulip_message_id=message_id,+ )+ content = attachment_result.updated_content+ accumulated_batch_upload_records += attachment_result.upload_records++ if attachment_result.upload_records != []:+ # Currently process_hosted_content_attachments only supports processeing+ # images so has_image is always true in this case.+ has_image = True+ has_link = True+ has_attachments = True+ else:+ has_image = False+ has_link = False+ has_attachments = False+zulip_message = build_message(topic_name=topic_name,date_sent=get_timestamp_from_message(message),message_id=message_id,content=content,rendered_content=None,- user_id=microsoft_teams_user_id_to_zulip_user_id[microsoft_teams_sender_id],+ user_id=user_id,recipient_id=recipient_id,realm_id=realm_id,is_channel_message=not is_direct_message_type,- # TODO: Process links and attachments- has_image=False,- has_link=False,- has_attachment=False,+ has_image=has_image,+ has_link=has_link,+ has_attachment=has_attachments,is_direct_message_type=is_direct_message_type,)zerver_messages.append(zulip_message)@@ -498,6 +690,7 @@ def process_messages(return MessageConversionResult(zerver_messages=zerver_messages,zerver_usermessages=zerver_usermessage,+ upload_records=accumulated_batch_upload_records,)@@ -523,13 +716,15 @@ def get_batched_export_message_data(def convert_messages(added_teams: dict[str, TeamMetadata],domain_name: str,+ microsoft_graph_api_token: str,microsoft_teams_user_id_to_zulip_user_id: MicrosoftTeamsUserIdToZulipUserIdT,output_dir: str,+ processes: int,realm_id: int,realm: dict[str, Any],teams_data_dir: str,chunk_size: int = MESSAGE_BATCH_CHUNK_SIZE,-) -> None:+) -> tuple[list[UploadRecordData], list[AttachmentRecordData]]:microsoft_teams_channel_metadata: dict[str, ChannelMetadata] = {}subscriber_map = make_subscriber_map(zerver_subscription=realm["zerver_subscription"],@@ -558,29 +753,42 @@ def convert_messages(membership_type=team_channel["MembershipType"],team_id=team_id,)-- dump_file_id = 1- for message_chunk in get_batched_export_message_data(message_file_paths, chunk_size):- conversion_result = process_messages(- added_teams=added_teams,- channel_metadata=microsoft_teams_channel_metadata,- domain_name=domain_name,- messages=message_chunk,- microsoft_teams_user_id_to_zulip_user_id=microsoft_teams_user_id_to_zulip_user_id,- realm=realm,- realm_id=realm_id,- subscriber_map=subscriber_map,- )-- create_converted_data_files(- dict(- zerver_message=conversion_result.zerver_messages,- zerver_usermessage=conversion_result.zerver_usermessages,- ),- output_dir,- f"/messages-{dump_file_id:06}.json",- )- dump_file_id += 1+ total_attachment_records: list[AttachmentRecordData] = []+ total_accumulated_upload_records: list[UploadRecordData] = []+ with run_parallel_queue(+ partial(+ download_and_export_microsoft_teams_upload_file, total_attachment_records, output_dir+ ),+ processes,+ catch=True,+ report_every=100,+ report=lambda count: logging.info("Downloaded %s attachments", count),+ ) as do_download_and_export_upload_file:+ dump_file_id = 1+ for message_chunk in get_batched_export_message_data(message_file_paths, chunk_size):+ conversion_result = process_messages(+ added_teams=added_teams,+ channel_metadata=microsoft_teams_channel_metadata,+ do_download_and_export_upload_file=do_download_and_export_upload_file,+ domain_name=domain_name,+ messages=message_chunk,+ microsoft_graph_api_token=microsoft_graph_api_token,+ microsoft_teams_user_id_to_zulip_user_id=microsoft_teams_user_id_to_zulip_user_id,+ realm=realm,+ realm_id=realm_id,+ subscriber_map=subscriber_map,+ )+ total_accumulated_upload_records += conversion_result.upload_records+ create_converted_data_files(+ dict(+ zerver_message=conversion_result.zerver_messages,+ zerver_usermessage=conversion_result.zerver_usermessages,+ ),+ output_dir,+ f"/messages-{dump_file_id:06}.json",+ )+ dump_file_id += 1+ return (total_accumulated_upload_records, total_attachment_records)def do_convert_directory(@@ -625,23 +833,25 @@ def do_convert_directory(teams_data_dir=teams_data_dir,)- convert_messages(+ upload_records, attachment_records = convert_messages(added_teams=added_teams,domain_name=domain_name,+ microsoft_graph_api_token=microsoft_graph_api_token,microsoft_teams_user_id_to_zulip_user_id=microsoft_teams_user_id_to_zulip_user_id,output_dir=output_dir,+ processes=processes,realm_id=realm_id,realm=realm,teams_data_dir=teams_data_dir,)create_converted_data_files(realm, output_dir, "/realm.json")+ create_converted_data_files(upload_records, output_dir, "/uploads/records.json")+ attachment: dict[str, list[Any]] = {"zerver_attachment": attachment_records}+ create_converted_data_files(attachment, output_dir, "/attachment.json")# TODO:create_converted_data_files([], output_dir, "/emoji/records.json")create_converted_data_files([], output_dir, "/avatars/records.json")- create_converted_data_files([], output_dir, "/uploads/records.json")- attachment: dict[str, list[Any]] = {"zerver_attachment": []}- create_converted_data_files(attachment, output_dir, "/attachment.json")create_converted_data_files([], output_dir, "/realm_icons/records.json")do_common_export_processes(output_dir)diff --git a/zerver/tests/test_microsoft_teams_importer.py b/zerver/tests/test_microsoft_teams_importer.pyindex a8d1739409b..6bbf7921842 100644--- a/zerver/tests/test_microsoft_teams_importer.py+++ b/zerver/tests/test_microsoft_teams_importer.py@@ -1,8 +1,12 @@import jsonimport mathimport os+import re+import shutil+import tempfilefrom collections import defaultdictfrom collections.abc import Callable+from dataclasses import dataclassfrom functools import wrapsfrom typing import Any, Concatenate, TypeAliasfrom urllib.parse import parse_qs, urlsplit@@ -12,8 +16,9 @@ from django.utils.timezone import now as timezone_nowfrom requests import PreparedRequestfrom typing_extensions import ParamSpec-from zerver.data_import.import_util import get_data_file+from zerver.data_import.import_util import AttachmentRecordData, convert_html_to_text, get_data_filefrom zerver.data_import.microsoft_teams import (+ HOSTED_CONTENT_GRAPH_API_URL_REGEX,MICROSOFT_GRAPH_API_URL,ChannelMetadata,MicrosoftTeamsFieldsT,@@ -22,18 +27,23 @@ from zerver.data_import.microsoft_teams import (ODataQueryParameter,convert_users,do_convert_directory,+ download_and_export_microsoft_teams_upload_file,get_batched_export_message_data,get_microsoft_graph_api_data,get_microsoft_teams_sender_id_from_message,get_timestamp_from_message,get_user_roles,is_microsoft_teams_event_message,+ process_hosted_content_attachments,)from zerver.lib.export import MESSAGE_BATCH_CHUNK_SIZEfrom zerver.lib.import_realm import do_import_realm+from zerver.lib.partial import partialfrom zerver.lib.test_classes import ZulipTestCase+from zerver.lib.test_helpers import read_test_image_file+from zerver.lib.thumbnail import THUMBNAIL_ACCEPT_IMAGE_TYPESfrom zerver.lib.topic import messages_for_topic-from zerver.models.messages import Message+from zerver.models.messages import Attachment, Messagefrom zerver.models.realms import Realm, get_realmfrom zerver.models.streams import Stream, Subscriptionfrom zerver.models.users import UserProfile, get_system_bot@@ -216,6 +226,13 @@ def mock_microsoft_graph_api_calls("microsoft_graph_api_response_fixtures",),)+ responses.add(+ responses.GET,+ re.compile(HOSTED_CONTENT_GRAPH_API_URL_REGEX),+ body=read_test_image_file("img.png"),+ content_type="image/png",+ status=200,+ )test_func(self, *args, **kwargs)return _wrapped@@ -250,7 +267,10 @@ class MicrosoftTeamsImporterIntegrationTest(MicrosoftTeamsImportTestCase):raise AssertionError(f"Fixture file not found: {fixture_file_path}")with self.assertLogs(level="INFO"), self.settings(EXTERNAL_HOST="zulip.example.com"):do_convert_directory(- fixture_file_path, self.converted_file_output_dir, "MICROSOFT_GRAPH_API_TOKEN"+ fixture_file_path,+ self.converted_file_output_dir,+ "MICROSOFT_GRAPH_API_TOKEN",+ processes=1,)def import_microsoft_teams_export_fixture(self, fixture_folder: str) -> None:@@ -445,6 +465,36 @@ class MicrosoftTeamsImporterIntegrationTest(MicrosoftTeamsImportTestCase):len(messages_in_a_microsoft_team_channel), len(imported_messages_in_a_zulip_topic))+ imported_attachments = Attachment.objects.filter(realm=test_realm)+ self.assertTrue(imported_attachments.exists())+ message_ids_with_attachment = set()+ for attachment in imported_attachments:+ for message_with_attachment in Message.objects.filter(+ realm=test_realm, attachment=attachment+ ):+ self.assertTrue(message_with_attachment.has_attachment)+ self.assertEqual(+ message_with_attachment.has_image,+ attachment.content_type in THUMBNAIL_ACCEPT_IMAGE_TYPES,+ )+ self.assertTrue(message_with_attachment.has_link)+ assert isinstance(message_with_attachment.rendered_content, str)+ self.assertIn(+ f"/user_uploads/{attachment.path_id}", message_with_attachment.rendered_content+ )+ message_ids_with_attachment.add(message_with_attachment.id)++ # Make sure no weird message conversion with wrong has_attachment, has_link+ # and has_image property.+ self.assertSetEqual(+ message_ids_with_attachment,+ set(+ Message.objects.filter(+ realm=test_realm, has_link=True, has_attachment=True, has_image=True+ ).values_list("id", flat=True)+ ),+ )+class MicrosoftTeamsImporterUnitTest(MicrosoftTeamsImportTestCase):def convert_users_handler(@@ -655,3 +705,186 @@ class MicrosoftTeamsImporterUnitTest(MicrosoftTeamsImportTestCase):self.assertGreaterEqual(messages_left, len(batched_messages))message_batches += 1self.assertTrue(message_batches == expected_batch_amount)++ @responses.activate+ def test_process_hosted_content_attachments(self) -> None:+ responses.add(+ responses.GET,+ re.compile(HOSTED_CONTENT_GRAPH_API_URL_REGEX),+ body=read_test_image_file("img.png"),+ content_type="image/png",+ status=200,+ )++ @dataclass+ class MessageFixture:+ content: str+ hosted_content_count: int+ test_name: str+ is_direct_message_type: bool+ teams_message_id: str = "T"+ zulip_message_id: int = 0+ zulip_user_id: int = 0++ message_fixtures: list[MessageFixture] = [+ # This is actual decoded content from a message in messages_1d513e46-d8cd-41db-b84f-381fe5730794.json+ # The original message was just some text followed by an image.+ MessageFixture(+ content=convert_html_to_text(+ """+ <ul>+ <li>dashes are ok</li>+ <li>asterisks are ok</li>+ </ul>+ <p>+ Pluses are not counted as bullet point</p>+ <p> </p>+ <p>Rendered:</p>+ <p>+ <img+ src="https://graph.microsoft.com/v1.0/teams/1d513e46-d8cd-41db-b84f-381fe5730794/channels/19:[email protected]/messages/1755002994809/hostedContents/aWQ9eF8wLXd1cy1kNi0zZDZkYmNiODA0OGFhODhmMWMxY2Q1N2ZhYWIzYzRhZCx0eXBlPTEsdXJsPWh0dHBzOi8vdXMtYXBpLmFzbS5za3lwZS5jb20vdjEvb2JqZWN0cy8wLXd1cy1kNi0zZDZkYmNiODA0OGFhODhmMWMxY2Q1N2ZhYWIzYzRhZC92aWV3cy9pbWdv/$value"+ width="1189"+ height="208"+ alt="image"+ itemid="0-wus-d6-3d6dbcb8048aa88f1c1cd57faab3c4ad">+ </p>+ """+ ),+ hosted_content_count=1,+ is_direct_message_type=False,+ test_name="text and an image",+ ),+ # Unprocessed converted html+ MessageFixture(+ content="Normal text and an [image](https://graph.microsoft.com/v1.0/teams/1d513e46-d8cd-41db-b84f-381fe5730794/channels/19:[email protected]/messages/1755002994809/hostedContents/aWQ9eF8wLXd1cy1kNi0zZDZkYmNiODA0OGFhODhmMWMxY2Q1N2ZhYWIzYzRhZCx0eXBlPTEsdXJsPWh0dHBzOi8vdXMtYXBpLmFzbS5za3lwZS5jb20vdjEvb2JqZWN0cy8wLXd1cy1kNi0zZDZkYmNiODA0OGFhODhmMWMxY2Q1N2ZhYWIzYzRhZC92aWV3cy9pbWdv/$value)",+ hosted_content_count=1,+ is_direct_message_type=False,+ test_name="text and an image 2",+ ),+ MessageFixture(+ content=(+ "First [image](https://graph.microsoft.com/v1.0/teams/1d513e46-d8cd-41db-b84f-381fe5730794/channels/19:[email protected]/messages/1755002994809/hostedContents/aWQ9eF8wLXd1cy1kNi0zZDZkYmNiODA0OGFhODhmMWMxY2Q1N2ZhYWIzYzRhZCx0eXBlPTEsdXJsPWh0dHBzOi8vdXMtYXBpLmFzbS5za3lwZS5jb20vdjEvb2JqZWN0cy8wLXd1cy1kNi0zZDZkYmNiODA0OGFhODhmMWMxY2Q1N2ZhYWIzYzRhZC92aWV3cy9pbWdv/$value)"+ "Second [image](https://graph.microsoft.com/v1.0/teams/1d513e46-d8cd-41db-b84f-381fe5730794/channels/19:[email protected]/messages/1755002994809/hostedContents/ABC/$value)"+ "Third [image](https://graph.microsoft.com/v1.0/teams/1d513e46-d8cd-41db-b84f-381fe5730794/channels/19:[email protected]/messages/1755002994809/hostedContents/DEF/$value)"+ ),+ hosted_content_count=3,+ is_direct_message_type=False,+ test_name="multiple images",+ ),+ # This is actual decoded content from a message in messages_002145f2-eaba-4962-997d-6d841a9f50af.json+ # The original message was just two custom emojis, nothing else. convert_html_to_text doesn't know+ # how to process MS Teams-specific tags such as <customemoji>, so this will be converted to empty+ # string.+ MessageFixture(+ content=convert_html_to_text(+ """+ <p>+ <span>+ <customemoji+ id="MC13dXMtZDEtZWMzY2I4NmY3MmM5YzBjNGJlMjE2Zjk3MTM1MDZkNTQ="+ alt="notif-bot"+ source="https://graph.microsoft.com/v1.0/teams/002145f2-eaba-4962-997d-6d841a9f50af/channels/19:[email protected]/messages/1759320958611/hostedContents/aWQ9LHR5cGU9MSx1cmw9aHR0cHM6Ly91cy1wcm9kLmFzeW5jZ3cudGVhbXMubWljcm9zb2Z0LmNvbS92MS9vYmplY3RzLzAtd3VzLWQxLWVjM2NiODZmNzJjOWMwYzRiZTIxNmY5NzEzNTA2ZDU0L3ZpZXdzL2ltZ3QyX2FuaW0=/$value">+ </customemoji>+ </span>+ <span>+ <customemoji+ id="MC13dXMtZDItMWNmOWZmOGQ2OTFiOGM5ZjExYzhhM2ZhMzJiMzFlMDU="+ alt="zlp-logo"+ source="https://graph.microsoft.com/v1.0/teams/002145f2-eaba-4962-997d-6d841a9f50af/channels/19:[email protected]/messages/1759320958611/hostedContents/aWQ9LHR5cGU9MSx1cmw9aHR0cHM6Ly91cy1wcm9kLmFzeW5jZ3cudGVhbXMubWljcm9zb2Z0LmNvbS92MS9vYmplY3RzLzAtd3VzLWQyLTFjZjlmZjhkNjkxYjhjOWYxMWM4YTNmYTMyYjMxZTA1L3ZpZXdzL2ltZ3QyX2FuaW0=/$value">+ </customemoji>+ </span>+ </p>+ """+ ),+ hosted_content_count=0,+ is_direct_message_type=False,+ test_name="two custom emojis",+ ),+ MessageFixture(+ content="Normal message",+ hosted_content_count=0,+ is_direct_message_type=False,+ test_name="text only",+ ),+ MessageFixture(+ content="MS Sharepoint attachment URL [image](https://zulipchat.sharepoint.com/sites/Community/Shared Documents/General/wp12245700.jpg)",+ hosted_content_count=0,+ is_direct_message_type=False,+ test_name="text and other URL",+ ),+ MessageFixture(+ content=(+ "List all hosted content [invalid](https://graph.microsoft.com/v1.0/teams/FOO/channels/BAZ/hostedContents)"+ "Get a hosted content [valid](https://graph.microsoft.com/v1.0/teams/FOO/channels/BAZ/messages/BAR/hostedContents/QUX/$value)"+ ),+ hosted_content_count=1,+ is_direct_message_type=False,+ test_name="invalid get hosted content URL and a valid one",+ ),+ MessageFixture(+ content=(+ "DM [image](https://graph.microsoft.com/v1.0/chats/{chat-id}/messages/{message-id}/hostedContents/{hosted-content-id}/$value)"+ ),+ hosted_content_count=0,+ is_direct_message_type=True,+ test_name="DM hosted content",+ ),+ ]+ output_dir = tempfile.mkdtemp()+ realm_id = 0+ try:+ for id_count, fixture in enumerate(message_fixtures, 1):+ # Increment the fixture IDs to make them unique.+ fixture.teams_message_id += str(id_count)+ fixture.zulip_message_id += id_count+ # Multiply by 10 to help verify that we're computing each+ # object ID correctly for this code path.+ fixture.zulip_user_id += id_count * 10++ total_attachment_records: list[AttachmentRecordData] = []+ do_download_and_export_upload_file = partial(+ download_and_export_microsoft_teams_upload_file,+ total_attachment_records,+ output_dir,+ )+ with self.subTest(fixture.test_name):+ attachment_result = process_hosted_content_attachments(+ content=fixture.content,+ do_download_and_export_upload_file=do_download_and_export_upload_file,+ is_direct_message_type=fixture.is_direct_message_type,+ microsoft_graph_api_token="MICROSOFT_GRAPH_API_TOKEN",+ realm_id=realm_id,+ teams_message_id=fixture.teams_message_id,+ zulip_message_id=fixture.zulip_message_id,+ zulip_user_id=fixture.zulip_user_id,+ )++ self.assert_length(+ attachment_result.upload_records, fixture.hosted_content_count+ )+ self.assert_length(total_attachment_records, fixture.hosted_content_count)++ for upload_record in attachment_result.upload_records:+ self.assertEqual(upload_record.realm_id, realm_id)+ self.assertEqual(upload_record.user_profile_id, fixture.zulip_user_id)+ self.assertRegex(+ upload_record.path, rf"^{realm_id}/.*/.*/{fixture.teams_message_id}$"+ )+ upload_file = os.path.join(output_dir, "uploads", upload_record.path)+ self.assertTrue(os.path.exists(upload_file))+ self.assertIn(+ os.path.join("/user_uploads", upload_record.path),+ attachment_result.updated_content,+ )++ for attachment_record in total_attachment_records:+ self.assertEqual(attachment_record.realm, realm_id)+ self.assertListEqual(attachment_record.messages, [fixture.zulip_message_id])+ self.assertEqual(attachment_record.owner, fixture.zulip_user_id)+ self.assertEqual(attachment_record.content_type, "image/png")+ self.assertEqual(attachment_record.file_name, fixture.teams_message_id)+ self.assertRegex(+ attachment_record.path_id,+ rf"^{realm_id}/.*/.*/{fixture.teams_message_id}$",+ )+ finally:+ shutil.rmtree(output_dir)