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.

ms_teams_importer: Convert team messages.

PieterCK033af783438d
diff --git a/starlight_help/astro.config.mjs b/starlight_help/astro.config.mjs
index 6f033748078..edb97f3ff68 100644
--- a/starlight_help/astro.config.mjs
+++ b/starlight_help/astro.config.mjs
@@ -515,6 +515,7 @@ export default defineConfig({
label: "Import an organization",
items: [
"import-from-mattermost",
+ "import-from-microsoft-teams",
"import-from-slack",
"import-from-rocketchat",
"export-your-organization",
diff --git a/starlight_help/src/content/docs/import-from-microsoft-teams.mdx b/starlight_help/src/content/docs/import-from-microsoft-teams.mdx
index e7597c58aed..ecf0c5750fe 100644
--- a/starlight_help/src/content/docs/import-from-microsoft-teams.mdx
+++ b/starlight_help/src/content/docs/import-from-microsoft-teams.mdx
@@ -23,6 +23,7 @@ The import will include your organization's:
* **Name**
* **Users**, including names, emails, roles
* **Teams** as Zulip channels, including all user subscriptions
+* **Message history**, excluding direct messages and messages in private channels.
## Import process overview
@@ -205,11 +206,17 @@ tool:
Whether you are using Zulip Cloud or self-hosting Zulip, here are few notes to keep
in mind about the import process:
+* Any kind of mentions in messages are not converted to Zulip mentions.
* Custom emojis are not imported.
+* Direct messages are not imported.
* Meeting chats and recordings are not imported.
* Message attachments are not imported.
-* Message history are not imported.
+* Message edit history and system messages such as `@user_a added @user_b to the chat`
+ are not imported.
* Message reactions are not imported.
+* Message thread replies will be combined to the main topic.
+* Messages from deleted users are not imported.
+* Messages in private channels are not imported.
* Microsoft tenant's user roles are mapped to Zulip's [user
roles](/help/user-roles) in the following way:
| Microsoft Teams role | Zulip role |
diff --git a/zerver/data_import/microsoft_teams.py b/zerver/data_import/microsoft_teams.py
index d390f65eb3c..5e001a72fa5 100644
--- a/zerver/data_import/microsoft_teams.py
+++ b/zerver/data_import/microsoft_teams.py
@@ -1,7 +1,9 @@
import logging
import os
from collections import defaultdict
+from collections.abc import Iterable
from dataclasses import dataclass
+from datetime import datetime
from typing import Any, Literal, TypeAlias
from urllib.parse import SplitResult
@@ -11,18 +13,22 @@ from django.utils.timezone import now as timezone_now
from zerver.data_import.import_util import (
ZerverFieldsT,
+ build_message,
build_realm,
build_recipient,
build_stream,
build_subscription,
build_user_profile,
+ build_usermessages,
build_zerver_realm,
+ convert_html_to_text,
create_converted_data_files,
get_data_file,
+ make_subscriber_map,
validate_user_emails_for_import,
)
from zerver.data_import.sequencer import NEXT_ID
-from zerver.lib.export import do_common_export_processes
+from zerver.lib.export import MESSAGE_BATCH_CHUNK_SIZE, do_common_export_processes
from zerver.models.recipients import Recipient
from zerver.models.users import UserProfile
@@ -41,6 +47,20 @@ class TeamMetadata:
zulip_recipient_id: int
+@dataclass
+class ChannelMetadata:
+ """
+ "channel" is equivalent to Zulip topics.
+ """
+
+ display_name: str
+ is_favourite_by_default: bool
+ is_archived: bool
+ is_favorite_by_default: bool
+ membership_type: str
+ team_id: str
+
+
AddedTeamsT: TypeAlias = dict[str, TeamMetadata]
TeamIdToZulipRecipientIdT: TypeAlias = dict[str, int]
MicrosoftTeamsUserIdToZulipUserIdT: TypeAlias = dict[str, int]
@@ -341,6 +361,203 @@ def convert_users(
return microsoft_teams_user_id_to_zulip_user_id
+def get_timestamp_from_message(message: MicrosoftTeamsFieldsT) -> float:
+ return datetime.fromisoformat(message["CreatedDateTime"]).timestamp()
+
+
+def get_microsoft_teams_sender_id_from_message(message: MicrosoftTeamsFieldsT) -> str:
+ return message["From"]["User"]["Id"]
+
+
+def is_microsoft_teams_event_message(message: MicrosoftTeamsFieldsT) -> bool:
+ return message["MessageType"] == "unknownFutureValue" and message["From"] is None
+
+
+def process_messages(
+ added_teams: dict[str, TeamMetadata],
+ channel_metadata: None | dict[str, ChannelMetadata],
+ is_private: bool,
+ messages: list[MicrosoftTeamsFieldsT],
+ microsoft_teams_user_id_to_zulip_user_id: MicrosoftTeamsUserIdToZulipUserIdT,
+ realm_id: int,
+ subscriber_map: dict[int, set[int]],
+) -> tuple[list[ZerverFieldsT], list[ZerverFieldsT]]:
+ zerver_usermessage: list[ZerverFieldsT] = []
+ zerver_messages: list[ZerverFieldsT] = []
+ total_user_messages = 0
+ total_skipped_user_messages = 0
+ skipped_deleted_users_message = 0
+
+ for message in messages:
+ if is_microsoft_teams_event_message(message):
+ continue
+
+ message_content_type = message["Body"]["ContentType"]
+ if message_content_type == "html":
+ try:
+ content = convert_html_to_text(message["Body"]["Content"])
+ except Exception: # nocoverage
+ logging.warning(
+ "Error converting HTML to text for message: '%s'; continuing", content
+ )
+ logging.warning(str(message))
+ continue
+ else: # nocoverage
+ logging.warning("Unable to convert this message content type: %s", message_content_type)
+ continue
+
+ # Determine message type, private or channel.
+ if message["ChannelIdentity"] is not None:
+ if channel_metadata is None:
+ raise AssertionError("Failed to build channel data.")
+ current_channel = channel_metadata[message["ChannelIdentity"]["ChannelId"]]
+ if current_channel.membership_type == "private":
+ # Don't include private channel messages.
+ continue
+ topic_name = current_channel.display_name
+ is_direct_message_type = False
+ recipient_id = added_teams[message["ChannelIdentity"]["TeamId"]].zulip_recipient_id
+ else: # nocoverage
+ assert message["ChatId"] is not None
+ # TODO: Converting direct messages is not yet supported. Since
+ # subscription list and recipient map of direct message conversations
+ # are not listed, we have to manually build them as we iterate over
+ # the user messages.
+ continue
+
+ microsoft_teams_sender_id: str = get_microsoft_teams_sender_id_from_message(message)
+
+ if microsoft_teams_sender_id not in microsoft_teams_user_id_to_zulip_user_id:
+ # TODO: Deleted users are not included in the exported user list but their
+ # messages are still exported and point to the deactivated user as the sender.
+ skipped_deleted_users_message += 1
+ continue
+
+ message_id = NEXT_ID("message")
+ 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],
+ 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,
+ is_direct_message_type=is_direct_message_type,
+ )
+ zerver_messages.append(zulip_message)
+
+ (num_created, num_skipped) = build_usermessages(
+ zerver_usermessage=zerver_usermessage,
+ subscriber_map=subscriber_map,
+ recipient_id=recipient_id,
+ mentioned_user_ids=[],
+ message_id=message_id,
+ is_private=is_direct_message_type,
+ )
+
+ total_user_messages += num_created
+ total_skipped_user_messages += num_skipped
+
+ logging.debug(
+ "Created %s UserMessages; deferred %s due to long-term idle",
+ total_user_messages,
+ total_skipped_user_messages,
+ )
+
+ logging.info(
+ "Unable to convert %s message(s) from deleted users.",
+ skipped_deleted_users_message,
+ )
+
+ return (
+ zerver_messages,
+ zerver_usermessage,
+ )
+
+
+def get_batched_export_message_data(
+ message_data_paths: list[str], chunk_size: int = MESSAGE_BATCH_CHUNK_SIZE
+) -> Iterable[list[MicrosoftTeamsFieldsT]]:
+ batched_messages: list[MicrosoftTeamsFieldsT] = []
+ for path in message_data_paths:
+ messages = get_data_file(path)
+ # Teams export tool doesn't sort messages in chronological order.
+ # Sort Microsoft Teams messages by their ID, which is their date
+ # sent in unix time.
+ for message in sorted(messages, key=lambda m: int(m["Id"])):
+ if len(batched_messages) == chunk_size:
+ yield batched_messages
+ batched_messages.clear()
+ batched_messages.append(message)
+
+ if batched_messages:
+ yield batched_messages
+
+
+def convert_messages(
+ added_teams: dict[str, TeamMetadata],
+ microsoft_teams_user_id_to_zulip_user_id: MicrosoftTeamsUserIdToZulipUserIdT,
+ output_dir: str,
+ realm_id: int,
+ realm: dict[str, Any],
+ teams_data_dir: str,
+ chunk_size: int = MESSAGE_BATCH_CHUNK_SIZE,
+) -> None:
+ microsoft_teams_channel_metadata: dict[str, ChannelMetadata] = {}
+ subscriber_map = make_subscriber_map(
+ zerver_subscription=realm["zerver_subscription"],
+ )
+ team_data_folders = []
+ for f in os.listdir(teams_data_dir):
+ path = os.path.join(teams_data_dir, f)
+ if os.path.isdir(path):
+ team_data_folders.append(f)
+
+ message_file_paths = []
+ for team_id in team_data_folders:
+ team_data_folder = os.path.join(teams_data_dir, team_id)
+ team_messages_file_path = os.path.join(team_data_folder, f"messages_{team_id}.json")
+ message_file_paths.append(team_messages_file_path)
+
+ team_channels_list = get_data_file(
+ os.path.join(team_data_folder, f"channels_{team_id}.json")
+ )
+ for team_channel in team_channels_list:
+ microsoft_teams_channel_metadata[team_channel["Id"]] = ChannelMetadata(
+ display_name=team_channel["DisplayName"],
+ is_favourite_by_default=team_channel["IsFavoriteByDefault"],
+ is_archived=team_channel["IsArchived"],
+ is_favorite_by_default=team_channel["IsFavoriteByDefault"],
+ 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):
+ (zerver_messages, zerver_usermessage) = process_messages(
+ added_teams=added_teams,
+ channel_metadata=microsoft_teams_channel_metadata,
+ is_private=False,
+ messages=message_chunk,
+ microsoft_teams_user_id_to_zulip_user_id=microsoft_teams_user_id_to_zulip_user_id,
+ subscriber_map=subscriber_map,
+ realm_id=realm_id,
+ )
+
+ create_converted_data_files(
+ dict(zerver_message=zerver_messages, zerver_usermessage=zerver_usermessage),
+ output_dir,
+ f"/messages-{dump_file_id:06}.json",
+ )
+ dump_file_id += 1
+
+
def do_convert_directory(
microsoft_teams_dir: str,
output_dir: str,
@@ -376,13 +593,22 @@ def do_convert_directory(
teams_data_dir = os.path.join(microsoft_teams_dir, "teams")
- convert_teams_to_channels(
+ added_teams = convert_teams_to_channels(
microsoft_teams_user_id_to_zulip_user_id=microsoft_teams_user_id_to_zulip_user_id,
realm=realm,
realm_id=realm_id,
teams_data_dir=teams_data_dir,
)
+ convert_messages(
+ added_teams=added_teams,
+ microsoft_teams_user_id_to_zulip_user_id=microsoft_teams_user_id_to_zulip_user_id,
+ output_dir=output_dir,
+ realm_id=realm_id,
+ realm=realm,
+ teams_data_dir=teams_data_dir,
+ )
+
create_converted_data_files(realm, output_dir, "/realm.json")
# TODO:
create_converted_data_files([], output_dir, "/emoji/records.json")
diff --git a/zerver/tests/fixtures/microsoft_teams_fixtures/TeamsData_ZulipChat/teams/7c050abd-3cbb-448b-a9de-405f54cc14b2/channels_7c050abd-3cbb-448b-a9de-405f54cc14b2.json b/zerver/tests/fixtures/microsoft_teams_fixtures/TeamsData_ZulipChat/teams/7c050abd-3cbb-448b-a9de-405f54cc14b2/channels_7c050abd-3cbb-448b-a9de-405f54cc14b2.json
index db26f85293f..8f92ebe98b5 100644
--- a/zerver/tests/fixtures/microsoft_teams_fixtures/TeamsData_ZulipChat/teams/7c050abd-3cbb-448b-a9de-405f54cc14b2/channels_7c050abd-3cbb-448b-a9de-405f54cc14b2.json
+++ b/zerver/tests/fixtures/microsoft_teams_fixtures/TeamsData_ZulipChat/teams/7c050abd-3cbb-448b-a9de-405f54cc14b2/channels_7c050abd-3cbb-448b-a9de-405f54cc14b2.json
@@ -10,5 +10,17 @@
"WebUrl": "https://teams.cloud.microsoft/l/channel/19%3A---2pcguZ0vbfte2wmk0y31xdnjlFv2C1k7nyYXUc7A1%40thread.tacv2/Core%20team?groupId=7c050abd-3cbb-448b-a9de-405f54cc14b2\u0026tenantId=af4acab6-6476-4c2f-bef2-ff6479dd3940\u0026allowXTenantAccess=True\u0026ngc=True",
"MembershipType": "standard",
"IsArchived": false
+ },
+ {
+ "Id": "19:[email protected]",
+ "CreatedDateTime": "2025-11-04T12:35:30.736Z",
+ "DisplayName": "private channel",
+ "Description": null,
+ "IsFavoriteByDefault": null,
+ "Email": null,
+ "TenantId": "af4acab6-6476-4c2f-bef2-ff6479dd3940",
+ "WebUrl": "https://teams.cloud.microsoft/l/channel/19%3A42c4944387224bf79bcad3cb6809a335%40thread.tacv2/private%20channel?groupId=7c050abd-3cbb-448b-a9de-405f54cc14b2&tenantId=af4acab6-6476-4c2f-bef2-ff6479dd3940&allowXTenantAccess=True&ngc=True",
+ "MembershipType": "private",
+ "IsArchived": false
}
]
diff --git a/zerver/tests/fixtures/microsoft_teams_fixtures/TeamsData_ZulipChat/teams/7c050abd-3cbb-448b-a9de-405f54cc14b2/messages_7c050abd-3cbb-448b-a9de-405f54cc14b2.json b/zerver/tests/fixtures/microsoft_teams_fixtures/TeamsData_ZulipChat/teams/7c050abd-3cbb-448b-a9de-405f54cc14b2/messages_7c050abd-3cbb-448b-a9de-405f54cc14b2.json
index f42933ac7f6..f971d3ccadb 100644
--- a/zerver/tests/fixtures/microsoft_teams_fixtures/TeamsData_ZulipChat/teams/7c050abd-3cbb-448b-a9de-405f54cc14b2/messages_7c050abd-3cbb-448b-a9de-405f54cc14b2.json
+++ b/zerver/tests/fixtures/microsoft_teams_fixtures/TeamsData_ZulipChat/teams/7c050abd-3cbb-448b-a9de-405f54cc14b2/messages_7c050abd-3cbb-448b-a9de-405f54cc14b2.json
@@ -500,5 +500,92 @@
"TeamsAppUpgraded": null,
"TeamUnarchived": null
}
+ },
+ {
+ "Id": "1766591445649",
+ "ReplyToId": null,
+ "MessageType": "message",
+ "CreatedDateTime": "2025-12-24T15:50:45.649Z",
+ "LastModifiedDateTime": "2025-12-24T15:50:45.649Z",
+ "LastEditedDateTime": null,
+ "DeletedDateTime": null,
+ "Subject": "",
+ "Summary": null,
+ "ChatId": null,
+ "Importance": "normal",
+ "Locale": "en-us",
+ "WebUrl": "https://teams.microsoft.com/l/message/19%3A42c4944387224bf79bcad3cb6809a335%40thread.tacv2/1766591445649?groupId=7c050abd-3cbb-448b-a9de-405f54cc14b2&tenantId=af4acab6-6476-4c2f-bef2-ff6479dd3940&createdTime=1766591445649&parentMessageId=1766591445649",
+ "PolicyViolation": null,
+ "EventDetail": null,
+ "From": {
+ "Application": null,
+ "Device": null,
+ "User": {
+ "Id": "88cbf3c2-0810-4d32-aa19-863c12bf7be9",
+ "DisplayName": "Pieter K",
+ "UserIdentityType": "aadUser",
+ "TenantId": "af4acab6-6476-4c2f-bef2-ff6479dd3940"
+ }
+ },
+ "Body": {
+ "ContentType": "html",
+ "Content": "<p>Private message!</p>"
+ },
+ "ChannelIdentity": {
+ "TeamId": "7c050abd-3cbb-448b-a9de-405f54cc14b2",
+ "ChannelId": "19:[email protected]"
+ },
+ "Attachments": [],
+ "Mentions": [],
+ "Reactions": []
+ },
+ {
+ "Id": "1762259740970",
+ "ReplyToId": null,
+ "MessageType": "unknownFutureValue",
+ "CreatedDateTime": "2025-11-04T12:35:40.97Z",
+ "LastModifiedDateTime": "2025-11-04T12:35:40.97Z",
+ "LastEditedDateTime": null,
+ "DeletedDateTime": null,
+ "Subject": null,
+ "Summary": null,
+ "ChatId": null,
+ "Importance": "normal",
+ "Locale": "en-us",
+ "WebUrl": "https://teams.microsoft.com/l/message/19%3A42c4944387224bf79bcad3cb6809a335%40thread.tacv2/1762259740970?groupId=7c050abd-3cbb-448b-a9de-405f54cc14b2&tenantId=af4acab6-6476-4c2f-bef2-ff6479dd3940&createdTime=1762259740970&parentMessageId=1762259740970",
+ "From": null,
+ "PolicyViolation": null,
+ "Body": {
+ "ContentType": "html",
+ "Content": "<systemEventMessage/>"
+ },
+ "ChannelIdentity": {
+ "TeamId": "7c050abd-3cbb-448b-a9de-405f54cc14b2",
+ "ChannelId": "19:[email protected]"
+ },
+ "Attachments": [],
+ "Mentions": [],
+ "Reactions": [],
+ "EventDetail": {
+ "VisibleHistoryStartDateTime": "0001-01-01T00:00:00Z",
+ "Members": [
+ {
+ "Id": "16741626-4cd8-46cc-bf36-42ecc2b5fdce",
+ "DisplayName": null,
+ "UserIdentityType": "aadUser",
+ "TenantId": "af4acab6-6476-4c2f-bef2-ff6479dd3940"
+ }
+ ],
+ "Initiator": {
+ "Application": null,
+ "Device": null,
+ "User": {
+ "Id": "88cbf3c2-0810-4d32-aa19-863c12bf7be9",
+ "DisplayName": null,
+ "UserIdentityType": "aadUser",
+ "TenantId": "af4acab6-6476-4c2f-bef2-ff6479dd3940"
+ }
+ }
+ }
}
]
diff --git a/zerver/tests/test_microsoft_teams_importer.py b/zerver/tests/test_microsoft_teams_importer.py
index 596c9c562b3..f10dedfde19 100644
--- a/zerver/tests/test_microsoft_teams_importer.py
+++ b/zerver/tests/test_microsoft_teams_importer.py
@@ -1,5 +1,7 @@
import json
+import math
import os
+from collections import defaultdict
from collections.abc import Callable
from functools import wraps
from typing import Any, Concatenate, TypeAlias
@@ -10,24 +12,34 @@ from django.utils.timezone import now as timezone_now
from requests import PreparedRequest
from typing_extensions import ParamSpec
+from zerver.data_import.import_util import get_data_file
from zerver.data_import.microsoft_teams import (
MICROSOFT_GRAPH_API_URL,
+ ChannelMetadata,
MicrosoftTeamsFieldsT,
MicrosoftTeamsUserIdToZulipUserIdT,
MicrosoftTeamsUserRoleData,
ODataQueryParameter,
convert_users,
do_convert_directory,
+ 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,
)
+from zerver.lib.export import MESSAGE_BATCH_CHUNK_SIZE
from zerver.lib.import_realm import do_import_realm
from zerver.lib.test_classes import ZulipTestCase
+from zerver.lib.topic import messages_for_topic
+from zerver.models.messages import Message
from zerver.models.realms import get_realm
from zerver.models.recipients import Recipient
from zerver.models.streams import Stream, Subscription
-from zerver.models.users import UserProfile
+from zerver.models.users import UserProfile, get_system_bot
from zerver.tests.test_import_export import make_export_output_dir
+from zproject import settings
ParamT = ParamSpec("ParamT")
@@ -58,6 +70,8 @@ MICROSOFT_TEAMS_EXPORT_USER_ROLE_DATA = MicrosoftTeamsUserRoleData(
)
+PRIVATE_MICROSOFT_TEAMS_CHANNELS = ["19:[email protected]"]
+
EXPORTED_MICROSOFT_TEAMS_TEAM_ID: dict[str, str] = {
"Core team": "7c050abd-3cbb-448b-a9de-405f54cc14b2",
"Community": "002145f2-eaba-4962-997d-6d841a9f50af",
@@ -108,6 +122,38 @@ def get_exported_team_subscription_list(team_id: str) -> list[MicrosoftTeamsFiel
)
+def get_exported_team_message_list(team_id: str) -> list[MicrosoftTeamsFieldsT]:
+ test_class = ZulipTestCase()
+ return json.loads(
+ test_class.fixture_data(
+ f"messages_{team_id}.json",
+ f"microsoft_teams_fixtures/TeamsData_ZulipChat/teams/{team_id}",
+ )
+ )
+
+
+def get_exported_team_channel_metadata(team_id: str) -> dict[str, ChannelMetadata]:
+ test_class = ZulipTestCase()
+ microsoft_teams_channel_metadata = {}
+ team_channels = json.loads(
+ test_class.fixture_data(
+ f"channels_{team_id}.json",
+ f"microsoft_teams_fixtures/TeamsData_ZulipChat/teams/{team_id}",
+ )
+ )
+
+ for team_channel in team_channels:
+ microsoft_teams_channel_metadata[team_channel["Id"]] = ChannelMetadata(
+ display_name=team_channel["DisplayName"],
+ is_favourite_by_default=team_channel["IsFavoriteByDefault"],
+ is_archived=team_channel["IsArchived"],
+ is_favorite_by_default=team_channel["IsFavoriteByDefault"],
+ membership_type=team_channel["MembershipType"],
+ team_id=team_id,
+ )
+ return microsoft_teams_channel_metadata
+
+
def graph_api_users_callback(request: PreparedRequest) -> ResponseTuple:
assert request.url is not None
parsed = urlsplit(request.url)
@@ -288,6 +334,105 @@ class MicrosoftTeamsImporterIntegrationTest(MicrosoftTeamsImportTestCase):
}
self.assertSetEqual(expected_subscriber_emails, imported_channel_subscriber_emails)
+ def test_imported_channel_messages(self) -> None:
+ self.do_import_realm_fixture()
+ channel_name = "Core team"
+ exported_team_messages = get_exported_team_message_list(
+ EXPORTED_MICROSOFT_TEAMS_TEAM_ID[channel_name]
+ )
+ test_realm = get_realm(self.test_realm_subdomain)
+ channel = Stream.objects.get(
+ name=channel_name,
+ realm=test_realm,
+ )
+ assert channel.recipient is not None
+
+ convertable_exported_messages: list[MicrosoftTeamsFieldsT] = []
+ convertable_exported_message_datetimes: list[float] = []
+ exported_sender_messages_map: dict[str, list[float]] = defaultdict(list)
+ private_channel_message_exists: bool
+
+ for message in exported_team_messages:
+ if is_microsoft_teams_event_message(message):
+ continue
+ if message["ChannelIdentity"]["ChannelId"] in PRIVATE_MICROSOFT_TEAMS_CHANNELS:
+ private_channel_message_exists = True
+ continue
+ sender_id = get_microsoft_teams_sender_id_from_message(message)
+ if sender_id not in self.exported_user_data_map:
+ continue
+ sender_email = self.exported_user_data_map[sender_id]["Mail"]
+
+ convertable_exported_messages.append(message)
+ message_datetime = get_timestamp_from_message(message)
+ convertable_exported_message_datetimes.append(message_datetime)
+ exported_sender_messages_map[sender_email].append(message_datetime)
+ self.assertTrue(private_channel_message_exists)
+
+ imported_channel_messages = (
+ Message.objects.filter(
+ recipient=channel.recipient,
+ realm=test_realm,
+ )
+ .exclude(sender_id=get_system_bot(settings.WELCOME_BOT, test_realm.id).id)
+ .order_by("id")
+ )
+ self.assertTrue(imported_channel_messages.exists())
+
+ imported_message_datetimes: list[float] = []
+ imported_sender_messages_map: dict[str, list[float]] = defaultdict(list)
+ last_date_sent: float = float("-inf")
+
+ for imported_message in imported_channel_messages:
+ message_date_sent = imported_message.date_sent.timestamp()
+ # Imported messages are sorted chronologically.
+ self.assertLessEqual(last_date_sent, message_date_sent)
+ last_date_sent = max(last_date_sent, message_date_sent)
+
+ # Message content is not empty.
+ self.assertIsNotNone(imported_message.content)
+ self.assertIsNotNone(imported_message.rendered_content)
+
+ imported_message_datetimes.append(message_date_sent)
+ imported_sender_messages_map[imported_message.sender.email].append(message_date_sent)
+
+ self.assertListEqual(
+ sorted(imported_message_datetimes),
+ sorted(convertable_exported_message_datetimes),
+ )
+
+ # Message sender is correct.
+ for sender_email, exported_message_datetimes in exported_sender_messages_map.items():
+ self.assertListEqual(
+ sorted(exported_message_datetimes),
+ sorted(imported_sender_messages_map[sender_email]),
+ )
+
+ microsoft_team_channel_metadata = get_exported_team_channel_metadata(
+ EXPORTED_MICROSOFT_TEAMS_TEAM_ID[channel_name]
+ )
+
+ # Microsoft Teams channels are correctly converted and imported
+ # as Zulip topics.
+ for (
+ microsoft_team_channel_id,
+ microsoft_team_channel_data,
+ ) in microsoft_team_channel_metadata.items():
+ messages_in_a_microsoft_team_channel = [
+ m
+ for m in convertable_exported_messages
+ if m["ChannelIdentity"]["ChannelId"] == microsoft_team_channel_id
+ ]
+
+ topic_name = microsoft_team_channel_data.display_name
+
+ imported_messages_in_a_zulip_topic = messages_for_topic(
+ test_realm.id, channel.recipient.id, topic_name
+ )
+ self.assertEqual(
+ len(messages_in_a_microsoft_team_channel), len(imported_messages_in_a_zulip_topic)
+ )
+
class MicrosoftTeamsImporterUnitTest(MicrosoftTeamsImportTestCase):
def convert_users_handler(
@@ -491,3 +636,34 @@ class MicrosoftTeamsImporterUnitTest(MicrosoftTeamsImportTestCase):
if user["Mail"] not in GUEST_USER_EMAILS
}
self.assertSetEqual(result_user_ids, expected_member_users)
+
+ def test_get_batched_export_message_data(self) -> None:
+ # Load a couple separate files to see how it handles combining and batching
+ # messages from multiple files.
+ message_file_paths = [
+ self.fixture_file_name(
+ "TeamsData_ZulipChat/teams/7c050abd-3cbb-448b-a9de-405f54cc14b2/messages_7c050abd-3cbb-448b-a9de-405f54cc14b2.json",
+ "microsoft_teams_fixtures",
+ ),
+ self.fixture_file_name(
+ "TeamsData_ZulipChat/teams/2a00a70a-00f5-4da5-8618-8281194f0de0/messages_2a00a70a-00f5-4da5-8618-8281194f0de0.json",
+ "microsoft_teams_fixtures",
+ ),
+ ]
+ total_messages = 0
+ for path in message_file_paths:
+ total_messages += len(get_data_file(path))
+
+ chunk_sizes = [5, 10, MESSAGE_BATCH_CHUNK_SIZE]
+ for chunk_size in chunk_sizes:
+ message_batches = 0
+ expected_batch_amount = math.ceil(total_messages / chunk_size)
+ messages_left = total_messages
+ for batched_messages in get_batched_export_message_data(message_file_paths, chunk_size):
+ if chunk_size <= messages_left:
+ self.assertGreaterEqual(chunk_size, len(batched_messages))
+ messages_left -= len(batched_messages)
+ else:
+ self.assertGreaterEqual(messages_left, len(batched_messages))
+ message_batches += 1
+ self.assertTrue(message_batches == expected_batch_amount)