mattermost-mobile/app/utils/gallery/index.test.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

259 lines
9.4 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {Image, ImageRef} from 'expo-image';
import {DeviceEventEmitter, Keyboard, View} from 'react-native';
import {Navigation} from 'react-native-navigation';
import {measure, type AnimatedRef} from 'react-native-reanimated';
import {waitFor} from '@test/intl-test-helper';
import {clamp, clampVelocity, fileToGalleryItem, freezeOtherScreens, friction, galleryItemToFileInfo, getImageSize, getShouldRender, measureItem, measureViewInWindow, openGalleryAtIndex, typedMemo} from '.';
import type {GalleryItemType, GalleryManagerSharedValues} from '@typings/screens/gallery';
jest.mock('@screens/navigation', () => ({
showOverlay: jest.fn(),
}));
// Mock react-native-reanimated measure function
jest.mock('react-native-reanimated', () => ({
measure: jest.fn(() => ({
pageX: 100,
pageY: 200,
width: 300,
height: 400,
})),
}));
describe('Gallery utils', () => {
afterAll(() => {
jest.clearAllMocks();
});
describe('clamp', () => {
it('should clamp a value within the given bounds', () => {
expect(clamp(5, 1, 10)).toBe(5);
expect(clamp(-5, 0, 10)).toBe(0);
expect(clamp(15, 0, 10)).toBe(10);
});
});
describe('clampVelocity', () => {
it('should clamp positive velocity within the given bounds', () => {
expect(clampVelocity(5, 1, 10)).toBe(5);
expect(clampVelocity(0.5, 1, 10)).toBe(1);
expect(clampVelocity(15, 1, 10)).toBe(10);
});
it('should clamp negative velocity within the given bounds', () => {
expect(clampVelocity(-5, 1, 10)).toBe(-5);
expect(clampVelocity(-0.5, 1, 10)).toBe(-1);
expect(clampVelocity(-15, 1, 10)).toBe(-10);
});
});
describe('fileToGalleryItem', () => {
it('should convert file info to gallery item with image type', () => {
const file = {
extension: 'jpg',
height: 600,
id: '123',
mime_type: 'image/jpeg',
name: 'test-image',
post_id: 'post123',
size: 5000,
localPath: '/path/to/image.jpg',
width: 800,
} as FileInfo;
const result = fileToGalleryItem(file);
expect(result.type).toBe('image');
expect(result.uri).toBe(file.localPath);
});
it('should convert file info to gallery item with video type', () => {
const file = {
extension: 'mp4',
height: 600,
id: '123',
mime_type: 'video/mp4',
name: 'test-video',
post_id: 'post123',
size: 10000,
localPath: '/path/to/video.mp4',
mini_preview: '/path/to/preview.jpg',
width: 800,
} as FileInfo;
const result = fileToGalleryItem(file);
expect(result.type).toBe('video');
expect(result.posterUri).toBe(file.mini_preview);
});
it('should convert file info to gallery item with video type and assign a file id that starts with uid', () => {
const file = {
extension: 'mp4',
height: 600,
mime_type: 'video/mp4',
name: 'test-video',
post_id: 'post123',
size: 10000,
localPath: '/path/to/video.mp4',
mini_preview: '/path/to/preview.jpg',
width: 800,
} as FileInfo;
const result = fileToGalleryItem(file);
expect(result.id.startsWith('uid')).toBeTruthy();
});
});
describe('freezeOtherScreens', () => {
it('should emit freeze screen event', () => {
const emitSpy = jest.spyOn(DeviceEventEmitter, 'emit');
freezeOtherScreens(true);
expect(emitSpy).toHaveBeenCalledWith('FREEZE_SCREEN', true);
});
});
describe('friction', () => {
it('should calculate friction based on value', () => {
expect(friction(100)).toBeGreaterThan(1);
expect(friction(-100)).toBeLessThan(0);
});
});
describe('galleryItemToFileInfo', () => {
it('should convert gallery item to file info', () => {
const item = {
id: '123',
name: 'test-image',
width: 800,
height: 600,
extension: 'jpg',
mime_type: 'image/jpeg',
postId: 'post123',
authorId: 'user123',
} as GalleryItemType;
const result = galleryItemToFileInfo(item);
expect(result.id).toBe(item.id);
expect(result.name).toBe(item.name);
});
});
describe('getShouldRender', () => {
it('should return true if index is within range of active index', () => {
expect(getShouldRender(5, 5)).toBe(true);
expect(getShouldRender(6, 5)).toBe(true);
expect(getShouldRender(9, 5)).toBe(false);
});
});
describe('measureItem', () => {
it('should measure and set shared values', () => {
const ref = jest.fn() as unknown as AnimatedRef<any>;
const sharedValues = {
x: {value: 0},
y: {value: 0},
width: {value: 0},
height: {value: 0},
} as GalleryManagerSharedValues;
measureItem(ref, sharedValues);
expect(sharedValues.x.value).toBe(100);
expect(sharedValues.y.value).toBe(200);
});
it('should measure and set shared values', () => {
const ref = jest.fn() as unknown as AnimatedRef<any>;
const sharedValues = {
x: {value: 0},
y: {value: 0},
width: {value: 0},
height: {value: 0},
} as GalleryManagerSharedValues;
measureItem(ref, sharedValues);
expect(sharedValues.x.value).toBe(100);
expect(sharedValues.y.value).toBe(200);
});
it('should handle measure exception and set shared values out of the viewport', () => {
const ref = jest.fn() as unknown as AnimatedRef<any>;
const sharedValues = {
x: {value: 0},
y: {value: 0},
width: {value: 0},
height: {value: 0},
} as GalleryManagerSharedValues;
(measure as jest.Mock).mockImplementationOnce(() => {
throw new Error('error');
});
measureItem(ref, sharedValues);
expect(sharedValues.x.value).toBe(999999);
expect(sharedValues.y.value).toBe(999999);
});
});
describe('openGalleryAtIndex', () => {
it('should open gallery and freeze other screens', async () => {
const emitSpy = jest.spyOn(DeviceEventEmitter, 'emit');
const galleryIdentifier = 'gallery1';
const initialIndex = 0;
const items = [{id: '1', name: 'item1'}, {id: '2', name: 'item2'}] as GalleryItemType[];
openGalleryAtIndex(galleryIdentifier, initialIndex, items);
expect(Keyboard.dismiss).toHaveBeenCalled();
expect(Navigation.setDefaultOptions).toHaveBeenCalled();
await waitFor(() => {
expect(emitSpy).toHaveBeenCalledWith('FREEZE_SCREEN', true);
});
});
});
describe('typedMemo', () => {
it('should memoize component', () => {
const component = jest.fn();
const memoizedComponent = typedMemo(component);
// @ts-expect-error type in typedef
expect(memoizedComponent.type).toBe(component);
});
});
describe('getImageSize', () => {
it('should resolve with image size', async () => {
jest.spyOn(Image, 'loadAsync').mockResolvedValue({
width: 800,
height: 600,
} as ImageRef);
const result = await getImageSize('serverUrl', 'test-uri', 'cacheKey');
expect(result).toEqual({width: 800, height: 600});
});
it('should reject on error', async () => {
jest.spyOn(Image, 'loadAsync').mockRejectedValue(new Error('Failed to get size'));
await expect(getImageSize('serverUrl', 'test-uri', 'cacheKey')).rejects.toThrow('Failed to get size');
});
});
describe('measureViewInWindow', () => {
it('should resolve with measured values when ref.current exists', async () => {
const measureMock = jest.fn((cb) => {
// x, y, width, height, pageX, pageY
cb(0, 0, 120, 80, 50, 60);
});
const ref = {current: {measure: measureMock}} as unknown as React.RefObject<View>;
const result = await measureViewInWindow(ref);
expect(result).toEqual({x: 50, y: 60, width: 120, height: 80});
expect(measureMock).toHaveBeenCalled();
});
it('should resolve with zeros when ref.current does not exist', async () => {
const ref = {current: null} as unknown as React.RefObject<View>;
const result = await measureViewInWindow(ref);
expect(result).toEqual({x: 0, y: 0, width: 0, height: 0});
});
});
});