Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
microsoft_teams_importer: Convert teams to channels.
PieterCK92796240227d
diff --git a/starlight_help/src/content/docs/import-from-microsoft-teams.mdx b/starlight_help/src/content/docs/import-from-microsoft-teams.mdxindex 604da70f3fe..e7597c58aed 100644--- a/starlight_help/src/content/docs/import-from-microsoft-teams.mdx+++ b/starlight_help/src/content/docs/import-from-microsoft-teams.mdx@@ -22,6 +22,7 @@ The import will include your organization's:* **Name*** **Users**, including names, emails, roles+* **Teams** as Zulip channels, including all user subscriptions## Import process overview@@ -216,7 +217,6 @@ in mind about the import process:| Global Administrator | Owner || Member | Member || Guest | Guest |-* Teams and channels are not imported.* The Teams export tool does not export organization settings, so you will need to[configure the settings for your Zuliporganization](/help/customize-organization-settings).diff --git a/zerver/data_import/microsoft_teams.py b/zerver/data_import/microsoft_teams.pyindex 29170661c6d..d390f65eb3c 100644--- a/zerver/data_import/microsoft_teams.py+++ b/zerver/data_import/microsoft_teams.py@@ -13,6 +13,7 @@ from zerver.data_import.import_util import (ZerverFieldsT,build_realm,build_recipient,+ build_stream,build_subscription,build_user_profile,build_zerver_realm,@@ -25,9 +26,115 @@ from zerver.lib.export import do_common_export_processesfrom zerver.models.recipients import Recipientfrom zerver.models.users import UserProfile++@dataclass+class TeamMetadata:+ """+ "team" is equivalent to a Zulip channel+ """++ description: str+ display_name: str+ visibility: Literal["public", "private"]+ is_archived: bool+ zulip_channel_id: int+ zulip_recipient_id: int+++AddedTeamsT: TypeAlias = dict[str, TeamMetadata]+TeamIdToZulipRecipientIdT: TypeAlias = dict[str, int]MicrosoftTeamsUserIdToZulipUserIdT: TypeAlias = dict[str, int]MicrosoftTeamsFieldsT: TypeAlias = dict[str, Any]+MICROSOFT_TEAMS_DEFAULT_ANNOUNCEMENTS_CHANNEL_NAME = "All company"+++def convert_teams_to_channels(+ microsoft_teams_user_id_to_zulip_user_id: MicrosoftTeamsUserIdToZulipUserIdT,+ realm: dict[str, Any],+ realm_id: int,+ teams_data_dir: str,+) -> AddedTeamsT:+ 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)++ logging.info("######### IMPORTING TEAMS STARTED #########\n")++ # Build teams subscription map+ team_id_to_zulip_subscriber_ids: dict[str, set[int]] = defaultdict(set)+ for team_id in team_data_folders:+ team_members_file_name = f"teamMembers_{team_id}.json"+ team_members_file_path = os.path.join(teams_data_dir, team_id, team_members_file_name)+ team_members: list[MicrosoftTeamsFieldsT] = get_data_file(team_members_file_path)++ for member in team_members:+ zulip_user_id = microsoft_teams_user_id_to_zulip_user_id[member["UserId"]]+ team_id_to_zulip_subscriber_ids[team_id].add(zulip_user_id)++ # Compile teamsSettings.json and teamsList.json and convert+ # teams to Zulip channels.+ teams_list = get_data_file(os.path.join(teams_data_dir, "teamsList.json"))+ teams_settings = get_data_file(os.path.join(teams_data_dir, "teamsSettings.json"))+ team_dict: dict[str, Any] = {team["GroupsId"]: team for team in teams_list}+ teams_metadata: AddedTeamsT = {}+ for team_settings in teams_settings:+ team_id = team_settings.get("Id")++ assert team_id and team_id in team_dict, (+ f"Team {team_id} appears in teamsSettings.json but not teamsList.json!"+ )++ compiled_team_data: MicrosoftTeamsFieldsT = {**team_dict[team_id], **team_settings}++ channel_id = NEXT_ID("channel")+ recipient_id = NEXT_ID("recipient")++ channel = build_stream(+ # Microsoft Teams export doesn't include teams creation date.+ date_created=float(timezone_now().timestamp()),+ realm_id=realm_id,+ name=compiled_team_data["Name"],+ description=compiled_team_data["Description"] or "",+ stream_id=channel_id,+ deactivated=compiled_team_data["IsArchived"],+ invite_only=compiled_team_data["Visibility"] == "private",+ )+ realm["zerver_stream"].append(channel)++ recipient = build_recipient(channel_id, recipient_id, Recipient.STREAM)+ realm["zerver_recipient"].append(recipient)++ for zulip_user_id in team_id_to_zulip_subscriber_ids[team_id]:+ sub = build_subscription(+ recipient_id=recipient_id,+ user_id=zulip_user_id,+ subscription_id=NEXT_ID("subscription"),+ )+ realm["zerver_subscription"].append(sub)++ # If the org uses the "All company" team, set it as the announcements channel.+ if (+ compiled_team_data["Name"] == MICROSOFT_TEAMS_DEFAULT_ANNOUNCEMENTS_CHANNEL_NAME+ ): # nocoverage+ realm["zerver_realm"][0]["new_stream_announcements_stream"] = channel_id+ realm["zerver_realm"][0]["zulip_update_announcements_stream"] = channel_id+ realm["zerver_realm"][0]["signup_announcements_stream"] = channel_id+ logging.info("Using the channel 'All company' as default announcements channel.")++ teams_metadata[team_id] = TeamMetadata(+ description=compiled_team_data["Description"],+ display_name=compiled_team_data["DisplayName"],+ visibility=compiled_team_data["Visibility"],+ is_archived=compiled_team_data["IsArchived"],+ zulip_channel_id=channel_id,+ zulip_recipient_id=recipient_id,+ )++ return teams_metadata+@dataclassclass MicrosoftTeamsUserRoleData:@@ -259,7 +366,7 @@ def do_convert_directory(realm["zerver_recipient"] = []realm["zerver_subscription"] = []- convert_users(+ microsoft_teams_user_id_to_zulip_user_id = convert_users(microsoft_teams_user_role_data=get_user_roles(microsoft_graph_api_token),realm=realm,realm_id=realm_id,@@ -267,6 +374,15 @@ def do_convert_directory(users_list=get_data_file(os.path.join(users_data_dir, "usersList.json")),)+ teams_data_dir = os.path.join(microsoft_teams_dir, "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,+ )+create_converted_data_files(realm, output_dir, "/realm.json")# TODO:create_converted_data_files([], output_dir, "/emoji/records.json")diff --git a/zerver/tests/test_microsoft_teams_importer.py b/zerver/tests/test_microsoft_teams_importer.pyindex 9f836dc19d8..596c9c562b3 100644--- a/zerver/tests/test_microsoft_teams_importer.py+++ b/zerver/tests/test_microsoft_teams_importer.py@@ -25,6 +25,7 @@ from zerver.lib.import_realm import do_import_realmfrom zerver.lib.test_classes import ZulipTestCasefrom zerver.models.realms import get_realmfrom zerver.models.recipients import Recipient+from zerver.models.streams import Stream, Subscriptionfrom zerver.models.users import UserProfilefrom zerver.tests.test_import_export import make_export_output_dir@@ -57,6 +58,56 @@ MICROSOFT_TEAMS_EXPORT_USER_ROLE_DATA = MicrosoftTeamsUserRoleData()+EXPORTED_MICROSOFT_TEAMS_TEAM_ID: dict[str, str] = {+ "Core team": "7c050abd-3cbb-448b-a9de-405f54cc14b2",+ "Community": "002145f2-eaba-4962-997d-6d841a9f50af",+ "Contributors": "2a00a70a-00f5-4da5-8618-8281194f0de0",+ "Feedback & support": "5e5f1988-3216-4ca0-83e9-18c04ecc7533",+ "Kandra Labs": "1d513e46-d8cd-41db-b84f-381fe5730794",+}+++def get_exported_microsoft_teams_user_data() -> list[MicrosoftTeamsFieldsT]:+ test_class = ZulipTestCase()+ return json.loads(+ test_class.fixture_data(+ "usersList.json", "microsoft_teams_fixtures/TeamsData_ZulipChat/users"+ )+ )+++def get_exported_team_data(team_id: str) -> MicrosoftTeamsFieldsT:+ test_class = ZulipTestCase()+ team_list = json.loads(+ test_class.fixture_data(+ "teamsList.json",+ "microsoft_teams_fixtures/TeamsData_ZulipChat/teams",+ )+ )++ team_list_data = next(team_data for team_data in team_list if team_id == team_data["GroupsId"])+ team_settings = json.loads(+ test_class.fixture_data(+ "teamsSettings.json",+ "microsoft_teams_fixtures/TeamsData_ZulipChat/teams",+ )+ )+ team_settings_data = next(+ team_data for team_data in team_settings if team_data["Id"] == team_id+ )+ return {**team_list_data, **team_settings_data}+++def get_exported_team_subscription_list(team_id: str) -> list[MicrosoftTeamsFieldsT]:+ test_class = ZulipTestCase()+ return json.loads(+ test_class.fixture_data(+ f"teamMembers_{team_id}.json",+ f"microsoft_teams_fixtures/TeamsData_ZulipChat/teams/{team_id}",+ )+ )++def graph_api_users_callback(request: PreparedRequest) -> ResponseTuple:assert request.url is not Noneparsed = urlsplit(request.url)@@ -134,6 +185,18 @@ class MicrosoftTeamsImportTestCase(ZulipTestCase):class MicrosoftTeamsImporterIntegrationTest(MicrosoftTeamsImportTestCase):+ def get_imported_channel_subscriber_emails(self, channel: str | Stream) -> set[str]:+ if isinstance(channel, str):+ imported_channel = Stream.objects.get(+ name=channel,+ realm=get_realm(self.test_realm_subdomain),+ )+ else:+ imported_channel = channel # nocoverage+ subscriptions = Subscription.objects.filter(recipient=imported_channel.recipient)+ users = {sub.user_profile.email for sub in subscriptions}+ return users+def convert_microsoft_teams_export_fixture(self, fixture_folder: str) -> None:fixture_file_path = self.fixture_file_name(fixture_folder, "microsoft_teams_fixtures")if not os.path.isdir(fixture_file_path):@@ -153,6 +216,8 @@ class MicrosoftTeamsImporterIntegrationTest(MicrosoftTeamsImportTestCase):self.converted_file_output_dir = make_export_output_dir()self.test_realm_subdomain = "test-import-teams-realm"self.import_microsoft_teams_export_fixture(fixture)+ exported_user_data = get_exported_microsoft_teams_user_data()+ self.exported_user_data_map = {u["Id"]: u for u in exported_user_data}def get_imported_realm_user_field_values(self, field: str, **kwargs: Any) -> list[str | int]:return list(@@ -193,6 +258,36 @@ class MicrosoftTeamsImporterIntegrationTest(MicrosoftTeamsImportTestCase):imported_user_full_names = self.get_imported_realm_user_field_values("full_name")self.assertEqual(sorted(raw_exported_user_full_names), sorted(imported_user_full_names))+ def test_imported_channels(self) -> None:+ self.do_import_realm_fixture()+ all_imported_channels = Stream.objects.filter(+ realm=get_realm(self.test_realm_subdomain),+ )++ self.assert_length(all_imported_channels, len(EXPORTED_MICROSOFT_TEAMS_TEAM_ID))++ for channel in all_imported_channels:+ channel_name = channel.name++ # Teams data are imported correctly+ raw_team_data = get_exported_team_data(EXPORTED_MICROSOFT_TEAMS_TEAM_ID[channel_name])+ self.assertEqual(channel_name, raw_team_data["Name"])+ self.assertEqual(channel.description, raw_team_data["Description"] or "")+ self.assertEqual(channel.deactivated, raw_team_data["IsArchived"])+ self.assertEqual(channel.invite_only, raw_team_data["Visibility"] == "private")++ # Teams subscription are imported correctly.+ imported_channel_subscriber_emails = self.get_imported_channel_subscriber_emails(+ channel_name+ )+ raw_subscription_list = get_exported_team_subscription_list(+ EXPORTED_MICROSOFT_TEAMS_TEAM_ID[channel_name]+ )+ expected_subscriber_emails: set[str] = {+ self.exported_user_data_map[sub["UserId"]]["Mail"] for sub in raw_subscription_list+ }+ self.assertSetEqual(expected_subscriber_emails, imported_channel_subscriber_emails)+class MicrosoftTeamsImporterUnitTest(MicrosoftTeamsImportTestCase):def convert_users_handler(