Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code Quality: Dynamically import mediainfo.js #12954

Merged
merged 4 commits into from
Jan 31, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion includes/Admin/Editor.php
Original file line number Diff line number Diff line change
Expand Up @@ -457,7 +457,7 @@ public function get_editor_settings(): array {
'encodeMarkup' => $this->decoder->supports_decoding(),
'metaBoxes' => $this->meta_boxes->get_meta_boxes_per_location(),
'ffmpegCoreUrl' => trailingslashit( WEBSTORIES_CDN_URL ) . 'js/@ffmpeg/core@0.11.0/dist/ffmpeg-core.js',
'mediainfoUrl' => trailingslashit( WEBSTORIES_CDN_URL ) . 'js/mediainfo.js@0.1.7/dist/mediainfo.min.js',
'mediainfoUrl' => trailingslashit( WEBSTORIES_CDN_URL ) . 'js/mediainfo.js@0.1.9/dist/MediaInfoModule.wasm',
'flags' => array_merge(
$this->experiments->get_experiment_statuses( 'general' ),
$this->experiments->get_experiment_statuses( 'editor' ),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,13 @@
* External dependencies
*/
import { renderHook } from '@testing-library/react-hooks';
import type { VideoResource } from '@googleforcreators/media';
import { ResourceType } from '@googleforcreators/media';

/**
* Internal dependencies
*/
import type { ConfigState } from '../../../../types';
import { ConfigProvider } from '../../../config';
import useMediaInfo from '../useMediaInfo';

Expand All @@ -30,10 +33,22 @@ jest.mock('@googleforcreators/tracking', () => ({
getTimeTracker: jest.fn(() => jest.fn()),
}));

const mockAnalyzeData = jest.fn();

jest.mock('mediainfo.js', () => ({
__esModule: true,
default: jest.fn(() =>
Promise.resolve({
analyzeData: mockAnalyzeData,
close: jest.fn(),
})
),
}));

function arrange() {
const configState = {
mediainfoUrl: 'https://example.com',
};
} as ConfigState;

return renderHook(() => useMediaInfo(), {
wrapper: ({ children }) => (
Expand All @@ -42,16 +57,8 @@ function arrange() {
});
}

const analyzeData = jest.fn();
const mediaInfo = jest.fn(() =>
Promise.resolve({
analyzeData,
close: jest.fn(),
})
);

const BASE_RESOURCE = {
type: 'video',
const BASE_RESOURCE: VideoResource = {
type: ResourceType.Video,
mimeType: 'video/webm',
creationDate: '2021-05-11T21:55:24',
src: 'http://test.example/video.webm',
Expand All @@ -65,6 +72,7 @@ const BASE_RESOURCE = {
alt: 'small-video',
sizes: {},
isOptimized: false,
isExternal: false,
baseColor: '#734727',
};

Expand Down Expand Up @@ -214,17 +222,8 @@ const MEDIAINFO_RESULT_WEBM = JSON.stringify({
});

describe('useMediaInfo', () => {
let mediaInfoScript;

beforeAll(() => {
// Tricks loadScriptOnce() into resolving immediately.
mediaInfoScript = document.createElement('script');
mediaInfoScript.src = 'https://example.com';
document.documentElement.appendChild(mediaInfoScript);

window.MediaInfo = mediaInfo;

analyzeData.mockImplementation(() =>
mockAnalyzeData.mockImplementation(() =>
Promise.resolve(
JSON.stringify({
media: {
Expand All @@ -236,13 +235,7 @@ describe('useMediaInfo', () => {
});

afterEach(() => {
mediaInfo.mockClear();
});

afterAll(() => {
document.documentElement.removeChild(mediaInfoScript);

delete window.MediaInfo;
mockAnalyzeData.mockClear();
});

describe('getFileInfo', () => {
Expand All @@ -264,7 +257,7 @@ describe('useMediaInfo', () => {
it('should return file info for muted mp4 file', async () => {
const { result } = arrange();

analyzeData.mockImplementation(() =>
mockAnalyzeData.mockImplementation(() =>
Promise.resolve(MEDIAINFO_RESULT_MP4)
);

Expand Down Expand Up @@ -292,7 +285,7 @@ describe('useMediaInfo', () => {
it('should return file info for webm file', async () => {
const { result } = arrange();

analyzeData.mockImplementation(() =>
mockAnalyzeData.mockImplementation(() =>
Promise.resolve(MEDIAINFO_RESULT_WEBM)
);

Expand Down Expand Up @@ -369,7 +362,7 @@ describe('useMediaInfo', () => {
});

it('should return false for large MP4 file', async () => {
analyzeData.mockImplementation(() =>
mockAnalyzeData.mockImplementation(() =>
Promise.resolve(MEDIAINFO_RESULT_MP4)
);

Expand All @@ -385,7 +378,7 @@ describe('useMediaInfo', () => {
});

it('should return true for small MP4 file', async () => {
analyzeData.mockImplementation(() =>
mockAnalyzeData.mockImplementation(() =>
Promise.resolve(MEDIAINFO_RESULT_MP4_SMALL)
);

Expand Down
32 changes: 9 additions & 23 deletions packages/story-editor/src/app/media/utils/useMediaInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,22 +92,6 @@ interface MediaInfoResult {
isMuted?: boolean;
}

function loadScriptOnce(url: string) {
if (document.querySelector(`script[src="${url}"]`)) {
return Promise.resolve();
}

return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.async = true;
script.crossOrigin = 'anonymous';
script.src = url;
script.addEventListener('load', resolve);
script.addEventListener('error', reject);
document.head.appendChild(script);
});
}

/**
* Determines whether the resource/file has small enough dimensions.
*
Expand Down Expand Up @@ -183,15 +167,17 @@ function useMediaInfo() {
const trackTiming = getTimeTracker('load_mediainfo');

try {
// This will expose the window.MediaInfo global.
await loadScriptOnce(mediainfoUrl);
const { default: MediaInfoFactory } = await import(
/* webpackChunkName: "chunk-mediainfo" */
/* webpackExports: "default" */
'mediainfo.js'
);

// If for some reason it's not available yet.
if (!window.MediaInfo) {
return null;
}
const mediaInfo = await MediaInfoFactory({
format: 'JSON',
locateFile: () => mediainfoUrl,
});

const mediaInfo = await window.MediaInfo({ format: 'JSON' });
const result: ResultObject = JSON.parse(
(await mediaInfo.analyzeData(getSize, readChunk)) as unknown as string
) as ResultObject;
Expand Down
2 changes: 2 additions & 0 deletions packages/story-editor/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
{ "path": "../tracking" }
],
"include": [
"src/**/test/**/*.ts",
"src/**/test/**/*.tsx",
"src/app/api",
"src/app/canvas",
"src/app/config",
Expand Down
7 changes: 7 additions & 0 deletions webpack.config.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,13 @@ const sharedConfig = {
// Fixes resolving packages in the monorepo so we use the "src" folder, not "dist".
exportsFields: ['customExports', 'exports'],
extensions: ['.ts', '.tsx', '.js', '.jsx', '.json', '.wasm'],
// To make loading mediainfo.js work.
fallback: {
fs: false,
path: false,
url: false,
module: false,
},
},
mode,
devtool: !isProduction ? 'source-map' : undefined,
Expand Down