mattermost-mobile/app/utils/draft/index.ts
Elias Nahum 44eb76bed7
feat(iOS): Add Microsoft Intune MAM integration with multi-server support (#9312)
* refactor: implement custom ExpoImage wrapper for cache control

Add ExpoImage component with automatic cacheKey/cachePath management and replace all expo-image imports across the app

* refactor(ios): convert Gekidou to CocoaPods

Migrate from Swift Package Manager to CocoaPods, add Keychain write operations, refactor notification handler to remove react-native-notifications headers, and upgrade Swift to 5.0

* npm audit

* update fastlane

* feat(ci): integrate Intune MAM for enterprise builds with strict OSS protection

Add Intune submodule, CI actions, Fastlane configuration, developer scripts, pre-commit hooks, and validation workflows to enable internal MAM builds while protecting OSS repository

* fix tests by mocking @mattermost/intune

* feat: implement Intune MAM integration with comprehensive security enforcement

Add IntuneManager, refactor SecurityManager/SessionManager for MAM policies, implement native OIDC auth flow, add biometric enforcement, conditional launch blocking, and file protection controls

* fix alerts when no server database is present

* Unify cache strategy

* fix emit config changed after it was stored in the db

* Handle Mid-Session Enrollment Detection

* fix ADALLogOverrideDisabled missing in Fastfile

* fix flow for initial enrollment

* fix and add unit tests

* enable Intune configuration for PR and beta builds, CLIENT_ID should be changed before actual release

* Update intune submodule with addressed feedback

* fix validate-intune-clean workflow

* feat(intune): add comprehensive error handling and SAML+Entra support

Add production-ready error handling for native Entra authentication with
user-friendly i18n messages, comprehensive test coverage, and support for
Entra login when server requires SAML.

* update i18n

* update intune submodule

* update build-pr token

* fix race condition between server auth and intune enrollment

* fix CI workflow to build with intune

* use deploy key for intune submodule

* set the config directly in the submodule .git

* debug injection

* try setting GIT_SSH_COMMAND

* remove action debug

* fix server url input

* match pod cache with intune hash

* Fastfile and envs

* have workflows check for intune/.git

* have ci cache intune frameworks as well

* update Fastlane to set no-cache to artifacts uploaded

* fix s3 upload

* fix pblist template

* Attempt to remove the cache control for PR uploads to s3

* use hash from commit for S3 path

* Implement crash-resilient selective wipe with automatic retry and add removeInternetPassword to Gekidou Keychain

* Fix surface errors from intune login

* fix postinstall scripts

* use cacheKey for draft md images

* remove unnecessary double await during test

* Have isMinimumLicenseTier accept valid license sku tier as target

* Add missing Auth error messages

* remove the last period for intune errors in i18n

* do not call unenroll with wipe on manual logout

* Fix tests and Intune error messages

* do not filter any SSO type regardless of which is used for Intune

* fix 412 to not retry

* fix tests, app logs sharing and share_extension avatar cache

* apply setScreenCapturePolicy on license change

Co-authored-by: Eva Sarafianou <eva.sarafianou@mattermost.com>

* re-apply screen capture on enrollment

Co-authored-by: Eva Sarafianou <eva.sarafianou@mattermost.com>

* use userData from intunr login and prevent getMe

Co-authored-by: Eva Sarafianou <eva.sarafianou@mattermost.com>

* Check for Biometrics and Jailbreak as we used to

---------

Co-authored-by: Eva Sarafianou <eva.sarafianou@mattermost.com>
2025-12-10 13:07:28 +02:00

247 lines
9 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {defineMessage, defineMessages, type IntlShape, type MessageDescriptor} from 'react-intl';
import {Alert, type AlertButton} from 'react-native';
import {type SwipeableMethods} from 'react-native-gesture-handler/ReanimatedSwipeable';
import {parseMarkdownImages, removeDraft, updateDraftMarkdownImageMetadata, updateDraftMessage} from '@actions/local/draft';
import {General} from '@constants';
import {CODE_REGEX} from '@constants/autocomplete';
type AlertCallback = (value?: string) => void;
export function errorBadChannel(intl: IntlShape) {
const message = defineMessage({
id: 'mobile.server_link.unreachable_channel.error',
defaultMessage: 'This link belongs to a deleted channel or to a channel to which you do not have access.',
});
return alertErrorWithFallback(intl, {}, message);
}
export function errorUnkownUser(intl: IntlShape) {
const message = defineMessage({
id: 'mobile.server_link.unreachable_user.error',
defaultMessage: 'We can\'t redirect you to the DM. The user specified is unknown.',
});
alertErrorWithFallback(intl, {}, message);
}
export function permalinkBadTeam(intl: IntlShape) {
const message = defineMessage({
id: 'mobile.server_link.unreachable_team.error',
defaultMessage: 'This link belongs to a deleted team or to a team to which you do not have access.',
});
alertErrorWithFallback(intl, {}, message);
}
export function alertErrorWithFallback(intl: IntlShape, error: any, fallback: MessageDescriptor, values?: Record<string, string>, buttons?: AlertButton[]) {
let msg = error?.message;
if (!msg || msg === 'Network request failed') {
msg = intl.formatMessage(fallback, values);
}
Alert.alert('', msg, buttons);
}
export function alertAttachmentFail(intl: IntlShape, accept: AlertCallback, cancel: AlertCallback) {
Alert.alert(
intl.formatMessage({
id: 'mobile.post_textbox.uploadFailedTitle',
defaultMessage: 'Attachment failure',
}),
intl.formatMessage({
id: 'mobile.post_textbox.uploadFailedDesc',
defaultMessage: 'Some attachments failed to upload to the server. Are you sure you want to post the message?',
}),
[{
text: intl.formatMessage({id: 'mobile.channel_info.alertNo', defaultMessage: 'No'}),
onPress: cancel,
}, {
text: intl.formatMessage({id: 'mobile.channel_info.alertYes', defaultMessage: 'Yes'}),
onPress: accept,
}],
);
}
export const textContainsAtAllAtChannel = (text: string) => {
const textWithoutCode = text.replace(CODE_REGEX, '');
return (/(?:\B|\b_+)@(channel|all)(?!(\.|-|_)*[^\W_])/i).test(textWithoutCode);
};
export const textContainsAtHere = (text: string) => {
const textWithoutCode = text.replace(CODE_REGEX, '');
return (/(?:\B|\b_+)@(here)(?!(\.|-|_)*[^\W_])/i).test(textWithoutCode);
};
const buildChannelWideMentionMessageMessages = defineMessages({
hereWithTimezones: {
id: 'mobile.post_textbox.entire_channel_here.message.with_timezones',
defaultMessage: 'By using @here you are about to send notifications up to {totalMembers, number} {totalMembers, plural, one {person} other {people}} in {timezones, number} {timezones, plural, one {timezone} other {timezones}}. Are you sure you want to do this?',
},
othersWithTimezones: {
id: 'mobile.post_textbox.entire_channel.message.with_timezones',
defaultMessage: 'By using @all or @channel you are about to send notifications to {totalMembers, number} {totalMembers, plural, one {person} other {people}} in {timezones, number} {timezones, plural, one {timezone} other {timezones}}. Are you sure you want to do this?',
},
here: {
id: 'mobile.post_textbox.entire_channel_here.message',
defaultMessage: 'By using @here you are about to send notifications to up to {totalMembers, number} {totalMembers, plural, one {person} other {people}}. Are you sure you want to do this?',
},
others: {
id: 'mobile.post_textbox.entire_channel.message',
defaultMessage: 'By using @all or @channel you are about to send notifications to {totalMembers, number} {totalMembers, plural, one {person} other {people}}. Are you sure you want to do this?',
},
});
export function buildChannelWideMentionMessage(intl: IntlShape, membersCount: number, channelTimezoneCount: number, atHere: boolean) {
let notifyAllMessage = '';
if (channelTimezoneCount) {
const message = atHere ? buildChannelWideMentionMessageMessages.hereWithTimezones : buildChannelWideMentionMessageMessages.othersWithTimezones;
notifyAllMessage = (
intl.formatMessage(
message,
{
totalMembers: membersCount - 1,
timezones: channelTimezoneCount,
},
)
);
} else {
const message = atHere ? buildChannelWideMentionMessageMessages.here : buildChannelWideMentionMessageMessages.others;
notifyAllMessage = (
intl.formatMessage(
message,
{
totalMembers: membersCount - 1,
},
)
);
}
return notifyAllMessage;
}
export function alertChannelWideMention(intl: IntlShape, notifyAllMessage: string, accept: AlertCallback, cancel: AlertCallback) {
const message = intl.formatMessage({
id: 'mobile.post_textbox.entire_channel.title',
defaultMessage: 'Confirm sending notifications to entire channel',
});
alertMessage(intl, message, notifyAllMessage, accept, cancel);
}
export function alertSendToGroups(intl: IntlShape, notifyAllMessage: string, accept: AlertCallback, cancel: AlertCallback) {
const message = intl.formatMessage({
id: 'mobile.post_textbox.groups.title',
defaultMessage: 'Confirm sending notifications to groups',
});
alertMessage(intl, message, notifyAllMessage, accept, cancel);
}
function alertMessage(intl: IntlShape, message: string, notifyAllMessage: string, accept: AlertCallback, cancel: AlertCallback) {
Alert.alert(
message,
notifyAllMessage,
[
{
text: intl.formatMessage({
id: 'mobile.post_textbox.entire_channel.cancel',
defaultMessage: 'Cancel',
}),
onPress: cancel,
},
{
text: intl.formatMessage({
id: 'mobile.post_textbox.entire_channel.confirm',
defaultMessage: 'Confirm',
}),
onPress: accept,
},
],
);
}
export const getStatusFromSlashCommand = (message: string) => {
const tokens = message.split(' ');
const command = tokens[0]?.substring(1);
return General.STATUS_COMMANDS.includes(command) ? command : '';
};
export function alertSlashCommandFailed(intl: IntlShape, error: string) {
Alert.alert(
intl.formatMessage({
id: 'mobile.commands.error_title',
defaultMessage: 'Error Executing Command',
}),
error,
);
}
export const handleDraftUpdate = async ({
serverUrl,
channelId,
rootId,
value,
}: {
serverUrl: string;
channelId: string;
rootId: string;
value: string;
}) => {
await updateDraftMessage(serverUrl, channelId, rootId, value);
const imageMetadata: Dictionary<PostImage | undefined> = {};
await parseMarkdownImages(serverUrl, value, imageMetadata);
if (Object.keys(imageMetadata).length !== 0) {
updateDraftMarkdownImageMetadata({serverUrl, channelId, rootId, imageMetadata});
}
};
export function deleteDraftConfirmation({intl, serverUrl, channelId, rootId, swipeable}: {
intl: IntlShape;
serverUrl: string;
channelId: string;
rootId: string;
swipeable?: React.RefObject<SwipeableMethods>;
}) {
const deleteDraft = async () => {
removeDraft(serverUrl, channelId, rootId);
};
const onDismiss = () => {
if (swipeable?.current) {
swipeable.current.close();
}
};
Alert.alert(
intl.formatMessage({
id: 'draft.options.delete.title',
defaultMessage: 'Delete draft',
}),
intl.formatMessage({
id: 'draft.options.delete.confirmation',
defaultMessage: 'Are you sure you want to delete this draft?',
}),
[
{
text: intl.formatMessage({
id: 'draft.options.delete.cancel',
defaultMessage: 'Cancel',
}),
style: 'cancel',
onPress: onDismiss,
},
{
text: intl.formatMessage({
id: 'draft.options.delete.confirm',
defaultMessage: 'Delete',
}),
onPress: deleteDraft,
},
],
);
}