mattermost-mobile/app/components/markdown/markdown_image/index.tsx
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

290 lines
11 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {useManagedConfig} from '@mattermost/react-native-emm';
import Clipboard from '@react-native-clipboard/clipboard';
import React, {useCallback, useMemo, useRef, useState} from 'react';
import {useIntl} from 'react-intl';
import {Platform, type StyleProp, Text, type TextStyle, TouchableWithoutFeedback, View} from 'react-native';
import Animated from 'react-native-reanimated';
import {SvgUri} from 'react-native-svg';
import parseUrl from 'url-parse';
import CompassIcon from '@components/compass_icon';
import FormattedText from '@components/formatted_text';
import ProgressiveImage from '@components/progressive_image';
import SlideUpPanelItem, {ITEM_HEIGHT} from '@components/slide_up_panel_item';
import TouchableWithFeedback from '@components/touchable_with_feedback';
import {GalleryInit} from '@context/gallery';
import {useServerUrl} from '@context/server';
import {useIsTablet} from '@hooks/device';
import {useGalleryItem} from '@hooks/gallery';
import {bottomSheet, dismissBottomSheet} from '@screens/navigation';
import {lookupMimeType} from '@utils/file';
import {fileToGalleryItem, openGalleryAtIndex} from '@utils/gallery';
import {bottomSheetSnapPoint} from '@utils/helpers';
import {calculateDimensions, getViewPortWidth, isGifTooLarge} from '@utils/images';
import {getMarkdownImageSize, removeImageProxyForKey} from '@utils/markdown';
import {urlSafeBase64Encode} from '@utils/security';
import {changeOpacity, makeStyleSheetFromTheme} from '@utils/theme';
import {secureGetFromRecord} from '@utils/types';
import {normalizeProtocol, safeDecodeURIComponent, tryOpenURL} from '@utils/url';
import {onOpenLinkError} from '@utils/url/links';
import type {GalleryItemType} from '@typings/screens/gallery';
type MarkdownImageProps = {
disabled?: boolean;
errorTextStyle: StyleProp<TextStyle>;
imagesMetadata: Record<string, PostImage | undefined>;
isReplyPost?: boolean;
linkDestination?: string;
layoutHeight?: number;
layoutWidth?: number;
location?: string;
postId: string;
source: string;
sourceSize?: {width?: number; height?: number};
theme: Theme;
}
const ANDROID_MAX_HEIGHT = 4096;
const ANDROID_MAX_WIDTH = 4096;
const getStyleSheet = makeStyleSheetFromTheme((theme: Theme) => ({
bottomSheet: {
flex: 1,
},
brokenImageIcon: {
width: 24,
height: 24,
},
container: {
marginVertical: 5,
top: 5,
},
svg: {
backgroundColor: changeOpacity(theme.centerChannelColor, 0.06),
borderRadius: 8,
flex: 1,
},
}));
const MarkdownImage = ({
disabled,
errorTextStyle,
imagesMetadata,
isReplyPost = false,
layoutWidth,
layoutHeight,
linkDestination,
location,
postId,
source,
sourceSize,
theme,
}: MarkdownImageProps) => {
const intl = useIntl();
const isTablet = useIsTablet();
const style = getStyleSheet(theme);
const managedConfig = useManagedConfig<ManagedConfig>();
const sourceKey = removeImageProxyForKey(source);
// Pattern suggested in https://react.dev/reference/react/useRef#avoiding-recreating-the-ref-contents
const genericFileRef = useRef<string | null>(null);
if (genericFileRef.current === null) {
genericFileRef.current = `uid-${urlSafeBase64Encode(sourceKey)}`;
}
const genericFileId = genericFileRef.current;
const metadata = secureGetFromRecord(imagesMetadata, sourceKey) || Object.values(imagesMetadata || {})[0];
const [failed, setFailed] = useState(() => isGifTooLarge(metadata));
const serverUrl = useServerUrl();
const galleryIdentifier = `${postId}-${genericFileId}-${location}`;
const fileInfo = useMemo(() => {
const uri = source.startsWith('/') ? serverUrl + source : source;
const originalSize = getMarkdownImageSize(isReplyPost, isTablet, sourceSize, metadata, layoutWidth, layoutHeight);
const decodedLink = safeDecodeURIComponent(uri);
let filename = parseUrl(decodedLink.substr(decodedLink.lastIndexOf('/'))).pathname.replace('/', '');
let extension = metadata?.format || filename.split('.').pop();
if (extension === filename) {
const ext = filename.indexOf('.') === -1 ? '.png' : filename.substring(filename.lastIndexOf('.'));
filename = `${filename}${ext}`;
extension = ext;
}
return {
id: genericFileId,
name: filename,
extension,
has_preview_image: true,
mime_type: lookupMimeType(filename),
post_id: postId,
uri,
width: originalSize.width,
height: originalSize.height,
} as FileInfo;
}, [source, serverUrl, isReplyPost, isTablet, sourceSize, metadata, layoutWidth, layoutHeight, genericFileId, postId]);
const handlePreviewImage = useCallback(() => {
const item: GalleryItemType = {
...fileToGalleryItem(fileInfo, undefined, undefined, 0, fileInfo.id),
mime_type: lookupMimeType(fileInfo.name),
type: 'image',
};
openGalleryAtIndex(galleryIdentifier, 0, [item]);
}, [fileInfo, galleryIdentifier]);
const {ref, onGestureEvent, styles} = useGalleryItem(
galleryIdentifier,
0,
handlePreviewImage,
);
const {height, width} = calculateDimensions(fileInfo.height, fileInfo.width, layoutWidth || getViewPortWidth(isReplyPost, isTablet));
const progressiveImageStyle = useMemo(() => ({width, height}), [width, height]);
const handleLinkPress = useCallback(() => {
if (linkDestination) {
const url = normalizeProtocol(linkDestination);
tryOpenURL(url, () => onOpenLinkError(intl));
}
}, [intl, linkDestination]);
const handleLinkLongPress = useCallback(() => {
if (managedConfig?.copyAndPasteProtection !== 'true') {
const renderContent = () => {
return (
<View
testID='at_mention.bottom_sheet'
style={style.bottomSheet}
>
<SlideUpPanelItem
leftIcon='content-copy'
onPress={() => {
dismissBottomSheet();
Clipboard.setString(linkDestination || source);
}}
testID='at_mention.bottom_sheet.copy_url'
text={intl.formatMessage({id: 'mobile.markdown.link.copy_url', defaultMessage: 'Copy URL'})}
/>
<SlideUpPanelItem
destructive={true}
leftIcon='cancel'
onPress={() => {
dismissBottomSheet();
}}
testID='at_mention.bottom_sheet.cancel'
text={intl.formatMessage({id: 'mobile.post.cancel', defaultMessage: 'Cancel'})}
/>
</View>
);
};
bottomSheet({
closeButtonId: 'close-mardown-image',
renderContent,
snapPoints: [1, bottomSheetSnapPoint(2, ITEM_HEIGHT)],
title: intl.formatMessage({id: 'post.options.title', defaultMessage: 'Options'}),
theme,
});
}
}, [managedConfig?.copyAndPasteProtection, intl, theme, style.bottomSheet, linkDestination, source]);
const handleOnError = useCallback(() => {
setFailed(true);
}, []);
if (failed) {
return (
<CompassIcon
color={theme.centerChannelColor}
name='file-image-broken-outline-large'
size={24}
/>
);
}
let image;
if (height && width) {
if (Platform.OS === 'android' && (height > ANDROID_MAX_HEIGHT || width > ANDROID_MAX_WIDTH)) {
// Android has a cap on the max image size that can be displayed
return (
<Text style={[errorTextStyle, style.container]}>
<FormattedText
id='mobile.markdown.image.too_large'
defaultMessage='Image exceeds max dimensions of {maxWidth} by {maxHeight}:'
values={{
maxWidth: ANDROID_MAX_WIDTH,
maxHeight: ANDROID_MAX_HEIGHT,
}}
/>
{' '}
</Text>
);
} else if (fileInfo.extension === 'svg') {
image = (
<SvgUri
uri={fileInfo.uri!}
style={{flex: 1, backgroundColor: changeOpacity(theme.centerChannelColor, 0.06), borderRadius: 8}}
width={width}
height={height}
onError={handleOnError}
/>
);
} else {
image = (
<TouchableWithoutFeedback
disabled={disabled}
onLongPress={handleLinkLongPress}
onPress={onGestureEvent}
>
<Animated.View style={[styles, {width, height}, style.container]}>
<ProgressiveImage
forwardRef={ref}
id={fileInfo.id!}
imageUri={fileInfo.uri}
onError={handleOnError}
contentFit='contain'
style={progressiveImageStyle}
theme={theme}
/>
</Animated.View>
</TouchableWithoutFeedback>
);
}
}
if (image && linkDestination && !disabled) {
image = (
<TouchableWithFeedback
onPress={handleLinkPress}
onLongPress={handleLinkLongPress}
style={[{width, height}, style.container]}
>
<ProgressiveImage
id={fileInfo.id!}
imageUri={fileInfo.uri}
onError={handleOnError}
contentFit='contain'
style={progressiveImageStyle}
theme={theme}
/>
</TouchableWithFeedback>
);
}
return (
<GalleryInit galleryIdentifier={galleryIdentifier}>
<Animated.View testID='markdown_image'>
{image}
</Animated.View>
</GalleryInit>
);
};
export default MarkdownImage;