Carlos Santos 3d4f04feb1 Migrate to pnpm
chore: migrate project to pnpm and update workspace configuration

- Added pnpm workspace configuration in pnpm-workspace.yaml to manage packages.
- Updated prepare.sh script to use pnpm for installing and building packages.
- Modified testapp/package.json scripts to use pnpm instead of npm.
- Enhanced tsconfig.client.json and tsconfig.json with additional options and exclusions.
- Updated typings README.md to reflect the use of pnpm for installation and building.

streamline build process in prepare script and update dependency installation

Refactor code structure for improved readability and maintainability

refactor: optimize Dockerfile for better layer caching and dependency installation

refactor: migrate typings from '@lib/typings/ce' to '@openvidu-meet/typings'

- Updated imports across multiple components and services to use the new '@openvidu-meet/typings' package.
- Removed legacy typings references and adjusted paths in the frontend and webcomponent projects.
- Cleaned up the typings package structure and added build scripts for TypeScript.
- Removed the sync-types.sh script as it is no longer needed with the new structure.
- Updated README and package.json files to reflect the new package name and structure.
feat: add nodemon configuration for API documentation updates and enhance development scripts

feat: implement type checking in watch mode and update development scripts

feat: enhance development scripts with wait-for-typings and watch-typings utilities

fix: remove obsolete sync:backend script and enhance dev script with preserveWatchOutput option

feat: enhance development scripts with typings guard and improve watch behavior

Refactors build and dev scripts

Simplifies and consolidates build and development-related scripts for improved maintainability.

- Updates the build process to be more streamlined.
- Improves the development workflow by consolidating common tasks.
- Removes redundant scripts.

Replaces prepare script with meet script

Replaces the old `prepare.sh` script with a new `meet.sh` script to provide a more user-friendly and comprehensive interface for building and managing the project.

- Integrates command-line arguments for different build targets.
- Includes documentation generation for web components and REST APIs.
- Provides improved error handling and user feedback.
- Simplifies the build process with `pnpm`.

chore: update typescript version to 5.9.2 across multiple package.json files
refactor: replace constructor injection with inject function for AppDataService

feat: add commands to build webcomponent and run unit tests

meet.sh: add end-to-end testing support for webcomponent with optional Playwright browser installation

chore: update pnpm version to 10 and streamline test commands in workflows

meet.sh: rename build_webcomponent_only to build_webcomponent and streamline dependency installation

gitignore: add test-results directory to ignore list

meet.sh: rename build_webcomponent_only to build_webcomponent for consistency

Updated pnpm-lock.yml

refactor: streamline build scripts and enhance service start options in meet.sh

ci: update OpenVidu Meet actions to use meet-pnpm-migration version

refactor: update import paths for WebComponentCommand and WebComponentEvent to use shared typings

fix: add moduleNameMapper for typings path in jest configuration

fix: correct action version syntax for OpenVidu Meet setup in workflow

fix: update typings imports to use shared @openvidu-meet/typings package

fix: add skip-install and skip-typings options to meet.sh and update workflows

meet.sh: add development mode command and update start services options

fix: format code in meeting.component.ts and remove unused export in public-api.ts

added openvidu-components-angular to the local workspace and watch for changes in dev mode

fix: update Node.js action to v5 and streamline build steps in wc-unit-test.yaml

fix: remove pnpm install from build scripts in package.json

fix: update backend unit test workflow and add test unit command in meet.sh

fix: update unit test command in package.json to use pnpm exec

Updates import path for LiveKit permissions

Updates the import path for LiveKit permissions to align with the new typings package location, ensuring the test suite remains functional after the project's dependencies are migrated.

fix: remove redundant dependency installation and build steps in start_services function

fix: update Node.js setup action version and adjust OpenVidu actions for pnpm migration

fix: update tsconfig.json to exclude specific type declaration paths

fix: remove deprecated dependencies and update openapi-generate-html version

fix: update build messages and streamline start commands for production and CI modes

fix: update OpenVidu Meet and Testapp actions to use main branch and streamline pre-startup commands

Refactors type import for auth mode

Updates the import path for the authentication transport mode type.

This change ensures consistency across the application by using a centralized type definition.

Refactors backend integration tests

Streamlines the backend integration test workflow.

Consolidates test jobs for better organization and efficiency.
Leverages matrix testing for recordings API with different storage providers.
Improves AWS runner management for recording tests.
Adds artifact cleanup to prevent storage bloat.

Sets up Node.js and pnpm

Adds Node.js and pnpm setup steps to the integration test workflow.

This enables the use of pnpm for managing dependencies during integration tests.

Refactors test commands to use pnpm exec

Updates the test commands in package.json to use `pnpm exec`
for running Jest.

This ensures that the Jest CLI is executed within the pnpm
managed environment, resolving potential path and dependency
issues.

Refactors imports to use the new typings package

Updates imports to use the new `@openvidu-meet/typings` package.
Removes now-unnecessary module name mappings.

This change is part of the pnpm migration, ensuring correct
resolution of shared types.

Enhances backend integration tests and updates Node.js setup

Simplifies integration tests execution

Updates integration test scripts to streamline execution.

- Uses a single, parameterized script to run all backend integration tests.
- Removes redundant prefixes from test script names.

Refactors jest configuration to include moduleNameMapper for improved module resolution

Updates Jest integration test commands to use experimental VM modules and adjusts TypeScript root directory settings for better output structure

Ensures OpenVidu Meet logs are uploaded

Guarantees OpenVidu Meet logs are uploaded as artifacts, regardless of test outcome.

Moves log upload to ensure consistent capture, and does so for all test scenarios.

Commented backend integration tests

Fix build script to specify TypeScript configuration file

Refactor integration test command to use pnpm bin for jest execution

Update integration test commands to use relative paths for Jest execution

Revert "Commented backend integration tests"

This reverts commit 1da8cddb55e29036c2a816244f4bc8b665ede581.

Change log upload condition to trigger on failure for OpenVidu Meet logs

Add caching step for OpenVidu local deployment images in backend integration tests

Revert "Add caching step for OpenVidu local deployment images in backend integration tests"

This reverts commit bf4692d168c671100a88c09853a460ec5417979d.

Enhance AWS runner setup with storage provider matrix and update job names for clarity

Refactor AWS runner setup to separate jobs for S3, ABS, and GCS, enhancing clarity and maintainability

Update README.md to enhance structure and clarity, including detailed sections on prerequisites, getting started, development, and documentation.

Refactor Dockerfile and entrypoint script, remove deprecated image creation scripts, and enhance meet.sh with Docker build functionality and base href support

Update README.md to reflect changes in Docker image build commands using meet.sh

Update package.json to correct versioning and remove redundant entries

Added browser sync for live reloading

chore: update @typescript-eslint packages to version 8.46.1 in frontend and pnpm-lock.yaml

fix: correct argument skipping logic and ensure typings are built in install_dependencies function

Adapt project structure

backend: add TypeScript type annotations for Router instances in route files

fix: update path for nodemon configuration in dev:rest-api-docs script

fix: update paths in webcomponent documentation generation scripts

fix: update Dockerfile and entrypoint script for correct directory structure and improve error handling

fix: update .dockerignore and Dockerfile for improved directory handling and permissions; add backend type checker script

Added all tests files

Updates OpenVidu Meet action refs to main

Updates the OpenVidu Meet GitHub Action references
in the CI workflows to point to the `main` branch.

This ensures that the workflows use the latest version
of the action.
2025-10-15 17:42:04 +02:00

404 lines
14 KiB
TypeScript

import { expect, FrameLocator, Locator, Page } from '@playwright/test';
import * as fs from 'fs';
import { PNG } from 'pngjs';
import { MeetRecordingAccess, MeetRoomConfig } from '../../../../typings/src/room-config';
import { MEET_API_KEY, MEET_API_URL, MEET_TESTAPP_URL } from '../config';
/**
* Gets a FrameLocator for an iframe inside a Shadow DOM
* @param page - Playwright page object
* @param componentSelector - Selector for the web component with Shadow DOM
* @param iframeSelector - Selector for the iframe within the Shadow DOM
* @returns FrameLocator that can be used to access iframe contents
*/
export async function getIframeInShadowDom(
page: Page,
componentSelector: string = 'openvidu-meet',
iframeSelector: string = 'iframe'
): Promise<FrameLocator> {
// Verify the component exists
await page.waitForSelector(componentSelector);
// Use frameLocator to access the iframe contents
return page.frameLocator(`${componentSelector} >>> ${iframeSelector}`);
}
/**
* Waits for an element inside an iframe within Shadow DOM
* @param page - Playwright page object
* @param elementSelector - Selector for the element inside the iframe
* @param options - Optional configuration
* @returns Locator for the found element
*/
export async function waitForElementInIframe(
page: Page,
elementSelector: string,
options: {
componentSelector?: string;
iframeSelector?: string;
timeout?: number;
state?: 'attached' | 'detached' | 'visible' | 'hidden';
} = {}
): Promise<Locator> {
const {
componentSelector = 'openvidu-meet',
iframeSelector = 'iframe',
timeout = 30000,
state = 'visible'
} = options;
// Get the iframe
const frameLocator = await getIframeInShadowDom(page, componentSelector, iframeSelector);
// Get element locator
const elementLocator = frameLocator.locator(elementSelector);
// Wait for the element with the specified state
await elementLocator.waitFor({ state, timeout });
return elementLocator;
}
// Interact with an element inside an iframe within Shadow DOM
export async function interactWithElementInIframe(
page: Page,
elementSelector: string,
options: {
action: 'click' | 'fill' | 'type';
value?: string; // Only needed for 'fill' or 'type' actions
timeout?: number;
} = {
action: 'click',
value: '',
timeout: 30000
}
): Promise<void> {
const { action, value = '', timeout = 30000 } = options;
const element = await waitForElementInIframe(page, elementSelector, { timeout });
// Perform the specified action
switch (action) {
case 'click':
await element.click();
break;
case 'fill':
await element.fill(value);
break;
default:
throw new Error(`Unsupported action: ${action}`);
}
}
// Helper function to get default room config
const getDefaultRoomConfig = (): MeetRoomConfig => ({
recording: {
enabled: true,
allowAccessTo: MeetRecordingAccess.ADMIN_MODERATOR_SPEAKER
},
chat: { enabled: true },
virtualBackground: { enabled: true }
});
// Helper function to create a room for testing
export const createTestRoom = async (roomName: string, config: MeetRoomConfig = getDefaultRoomConfig()) => {
const response = await fetch(`${MEET_API_URL}/api/v1/rooms`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': MEET_API_KEY
},
body: JSON.stringify({
roomName,
autoDeletionDate: new Date(Date.now() + 61 * 60 * 1000).getTime(), // 1 hour from now
config
})
});
if (!response.ok) {
const errorResponse = await response.json();
console.error('Error creating room:', errorResponse);
throw new Error(`Failed to create room: ${response.status}`);
}
const room = await response.json();
return room.roomId;
};
// Helper function to update room config via REST API
export const updateRoomConfig = async (roomId: string, config: any) => {
const response = await fetch(`${MEET_API_URL}/api/v1/rooms/${roomId}/config`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'x-api-key': MEET_API_KEY
},
body: JSON.stringify({ config })
});
if (!response.ok) {
throw new Error(`Failed to update room config: ${response.status} ${await response.text()}`);
}
return response.json();
};
// Helper function to delete a room
export const deleteTestRoom = async (roomId: string) => {
await fetch(`${MEET_API_URL}/api/v1/rooms/${roomId}`, {
method: 'DELETE',
headers: {
'x-api-key': MEET_API_KEY
}
});
};
export const deleteAllRecordings = async (page: Page) => {
await page.goto(MEET_TESTAPP_URL);
await page.waitForSelector('#delete-all-recordings-btn', { state: 'visible' });
await page.click('#delete-all-recordings-btn');
};
export const deleteAllRooms = async (page: Page) => {
await page.goto(MEET_TESTAPP_URL);
await page.waitForSelector('#delete-all-rooms-btn', { state: 'visible' });
await page.click('#delete-all-rooms-btn');
};
export const startStopRecording = async (page: Page, action: 'start' | 'stop') => {
const buttonSelector = action === 'start' ? '#recording-btn' : '#stop-recording-btn';
if (action === 'start') {
await openMoreOptionsMenu(page);
}
await waitForElementInIframe(page, buttonSelector, { state: 'visible' });
await interactWithElementInIframe(page, buttonSelector, { action: 'click' });
await page.waitForTimeout(500); // Wait for recording action to complete
if (action === 'start') {
await page.waitForSelector('.webhook-recordingUpdated', { timeout: 10000 });
}
if (action === 'stop') {
await page.waitForSelector('.webhook-recordingEnded', { timeout: 10000 });
}
};
export const prepareForJoiningRoom = async (page: Page, url: string, roomId: string) => {
await page.goto(url);
await page.waitForSelector('.rooms-container');
await page.waitForSelector(`#${roomId}`);
await page.click('.dropdown-button');
await page.waitForSelector('#join-as-moderator');
await page.waitForSelector('#join-as-speaker');
};
export const joinRoomAs = async (role: 'moderator' | 'speaker', pName: string, page: Page) => {
await page.click('#join-as-' + role);
const component = page.locator('openvidu-meet');
await expect(component).toBeVisible();
// Wait for participant name input and fill it
await waitForElementInIframe(page, '#participant-name-input', { state: 'visible' });
await interactWithElementInIframe(page, '#participant-name-input', {
action: 'fill',
value: pName
});
await interactWithElementInIframe(page, '#participant-name-submit', { action: 'click' });
// wait for prejoin page to load and join the room
await waitForElementInIframe(page, 'ov-pre-join', { state: 'visible' });
await interactWithElementInIframe(page, '#join-button', { action: 'click' });
await waitForElementInIframe(page, 'ov-session', { state: 'visible' });
};
export const accessRoomAs = async (role: 'moderator' | 'speaker', page: Page) => {
await page.click('#join-as-' + role);
const component = page.locator('openvidu-meet');
await expect(component).toBeVisible();
};
export const viewRecordingsAs = async (role: 'moderator' | 'speaker', page: Page) => {
await page.click('#join-as-' + role);
const component = page.locator('openvidu-meet');
await expect(component).toBeVisible();
await interactWithElementInIframe(page, '#view-recordings-btn', { action: 'click' });
};
export const leaveRoom = async (page: Page, role: 'moderator' | 'speaker' = 'speaker') => {
await interactWithElementInIframe(page, '#leave-btn', { action: 'click' });
if (role === 'moderator') {
await page.waitForTimeout(500); // Wait for leave animation
await interactWithElementInIframe(page, '#leave-option', { action: 'click' });
}
await page.waitForSelector('.event-left');
};
export const startScreenSharing = async (page: Page) => {
await interactWithElementInIframe(page, '#screenshare-btn', { action: 'click' });
await waitForElementInIframe(page, '#local-element-screen_share', { state: 'visible' });
};
export const stopScreenSharing = async (page: Page) => {
await interactWithElementInIframe(page, '#screenshare-btn', { action: 'click' });
await page.waitForTimeout(200); // Wait for screen menu
await interactWithElementInIframe(page, '#disable-screen-button', { action: 'click' });
await page.waitForTimeout(500); // Wait for screen to stop sharing
};
export const applyVirtualBackground = async (page: Page, backgroundId: string) => {
await interactWithElementInIframe(page, '#more-options-btn', { action: 'click' });
await page.waitForTimeout(500);
await interactWithElementInIframe(page, '#virtual-bg-btn', { action: 'click' });
await waitForElementInIframe(page, 'ov-background-effects-panel', { state: 'visible' });
await interactWithElementInIframe(page, `#effect-${backgroundId}`, { action: 'click' });
await page.waitForTimeout(2000); // Allow background processing time
await interactWithElementInIframe(page, '.panel-close-button', { action: 'click' });
await page.waitForTimeout(1000); // Wait panel to close
};
export const removeVirtualBackground = async (page: Page) => {
await interactWithElementInIframe(page, '#more-options-btn', { action: 'click' });
await page.waitForTimeout(500);
await interactWithElementInIframe(page, '#virtual-bg-btn', { action: 'click' });
await interactWithElementInIframe(page, '#no_effect-btn', { action: 'click' });
await page.waitForTimeout(500); // Wait for background to be removed
};
/**
* Analyzes the current video frame to determine if the virtual background has been applied
* by checking if most pixels are different from Chrome's synthetic green background
*/
export const isVirtualBackgroundApplied = async (
page: Page,
videoSelector: string = '.OV_video-element',
options: {
minChangedPixelsPercent?: number; // Minimum % of non-green pixels to consider background applied
saveDebugImages?: boolean; // Save images for debugging
} = {}
): Promise<boolean> => {
const {
minChangedPixelsPercent = 70, // At least 20% of pixels should be non-green
saveDebugImages = false
} = options;
try {
// Capture current video frame
const screenshotPath = `test-results/vbg_check_${Date.now()}.png`;
await saveScreenshot(page, screenshotPath, videoSelector);
// Read the captured image
const currentFrame = PNG.sync.read(fs.readFileSync(screenshotPath));
const { width, height } = currentFrame;
// Count green pixels (sample every 5th pixel for performance)
let greenPixels = 0;
let totalSampled = 0;
for (let y = 0; y < height; y += 5) {
for (let x = 0; x < width; x += 5) {
const idx = (width * y + x) << 2;
const r = currentFrame.data[idx];
const g = currentFrame.data[idx + 1];
const b = currentFrame.data[idx + 2];
totalSampled++;
if (isChromeSyntheticGreen(r, g, b)) {
greenPixels++;
}
}
}
const greenPercentage = (greenPixels / totalSampled) * 100;
const nonGreenPercentage = 100 - greenPercentage;
const backgroundApplied = nonGreenPercentage >= minChangedPixelsPercent;
console.log(
`Video Analysis: ${nonGreenPercentage.toFixed(1)}% non-green pixels - Background applied: ${backgroundApplied}`
);
// Cleanup
if (!saveDebugImages) {
fs.unlinkSync(screenshotPath);
}
return backgroundApplied;
} catch (error) {
console.error('Error checking virtual background:', error);
return false;
}
};
/**
* Detects if a pixel is part of Chrome's synthetic green screen
* Chrome's fake video can vary, but typically has these characteristics:
* - Green channel is dominant
* - Overall brightness suggests synthetic content
* - Color tends to be uniformly distributed
*/
const isChromeSyntheticGreen = (r: number, g: number, b: number): boolean => {
// Method 1: Classic bright green detection (loose tolerances)
const isBrightGreen = g > 150 && g > r + 50 && g > b + 50 && r < 100 && b < 100;
// Method 2: Detect greenish hues with high saturation
const isGreenish = g > Math.max(r, b) && g > 100;
const hasLowRedBlue = r + b < g * 0.6;
const isGreenDominant = isGreenish && hasLowRedBlue;
// Method 3: Check for uniform synthetic-looking colors
// Chrome often uses specific green values
const isTypicalChromeGreen =
(g >= 240 && r <= 50 && b <= 50) || // Very bright green
(g >= 200 && r <= 80 && b <= 80) || // Bright green
(g >= 160 && r <= 60 && b <= 60); // Medium green
// Method 4: HSV-like check - high green saturation
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const saturation = max > 0 ? (max - min) / max : 0;
const isHighSaturationGreen = g === max && saturation > 0.5 && g > 120;
// Return true if any of the methods detect green
return isBrightGreen || isGreenDominant || isTypicalChromeGreen || isHighSaturationGreen;
};
/**
* Helper function that waits for virtual background to be applied
*/
export const waitForVirtualBackgroundToApply = async (page: Page, maxWaitTime: number = 5000): Promise<boolean> => {
const startTime = Date.now();
while (Date.now() - startTime < maxWaitTime) {
const isApplied = await isVirtualBackgroundApplied(page);
if (isApplied) {
console.log('✅ Virtual background detected');
return true;
}
await page.waitForTimeout(500); // Check every 500ms
}
console.log('❌ Virtual background not detected after waiting');
return false;
};
export const saveScreenshot = async (page: Page, filename: string, selector: string) => {
const element = await waitForElementInIframe(page, selector);
await element.screenshot({ path: filename });
};
export const openMoreOptionsMenu = async (page: Page) => {
await waitForElementInIframe(page, '#toolbar', { state: 'visible' });
// Open more options menu
await interactWithElementInIframe(page, '#more-options-btn', { action: 'click' });
await page.waitForTimeout(500); // Wait for menu animation
};
export const closeMoreOptionsMenu = async (page: Page) => {
await interactWithElementInIframe(page, 'body', { action: 'click' });
await page.waitForTimeout(500); // Wait for menu to close
};