From d67be9f575b5ce5d380d5582a9f49af03f801c4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Blome?= <43345275+ssmid@users.noreply.github.com> Date: Wed, 7 Jun 2023 09:35:54 +0000 Subject: [PATCH 001/134] THR-1 h5p editor: temporary file storage (#4147) * Created H5P microservice * Add kubernetes files for h5p microservice * Added @lumieducation/h5p-server package * Don't use mock auth for testing * Fix api tests to use new TestApiClient * WIP: H5P editor: temp file storage * WIP: H5P editor: added data classes * resolve merge conflict leftovers * h5p editor: temp file storage implementation completed * h5p editor: temp file storage tests added * h5p editor: temp file storage moved * h5p editor: temp storage files moved * Update temporary-file-storage.ts Create temporary file folder --------- Co-authored-by: Marvin Rode Co-authored-by: Marvin Rode (Cap) <127723478+marode-cap@users.noreply.github.com> Co-authored-by: Andre Blome Co-authored-by: Stephan Krause <101647440+SteKrause@users.noreply.github.com> --- .../temporary-file-storage/file-stats.ts | 12 + .../temporary-file-storage.spec.ts | 254 ++++++++++++++++++ .../temporary-file-storage.ts | 165 ++++++++++++ .../temporary-file-storage/temporary-file.ts | 24 ++ config/default.schema.json | 13 + 5 files changed, 468 insertions(+) create mode 100644 apps/server/src/modules/h5p-editor/temporary-file-storage/file-stats.ts create mode 100644 apps/server/src/modules/h5p-editor/temporary-file-storage/temporary-file-storage.spec.ts create mode 100644 apps/server/src/modules/h5p-editor/temporary-file-storage/temporary-file-storage.ts create mode 100644 apps/server/src/modules/h5p-editor/temporary-file-storage/temporary-file.ts diff --git a/apps/server/src/modules/h5p-editor/temporary-file-storage/file-stats.ts b/apps/server/src/modules/h5p-editor/temporary-file-storage/file-stats.ts new file mode 100644 index 00000000000..7e9a03055b9 --- /dev/null +++ b/apps/server/src/modules/h5p-editor/temporary-file-storage/file-stats.ts @@ -0,0 +1,12 @@ +import { IFileStats } from '@lumieducation/h5p-server'; + +export class FileStats implements IFileStats { + birthtime: Date; + + size: number; + + constructor(birthtime: Date, size: number) { + this.birthtime = birthtime; + this.size = size; + } +} diff --git a/apps/server/src/modules/h5p-editor/temporary-file-storage/temporary-file-storage.spec.ts b/apps/server/src/modules/h5p-editor/temporary-file-storage/temporary-file-storage.spec.ts new file mode 100644 index 00000000000..e5109b37093 --- /dev/null +++ b/apps/server/src/modules/h5p-editor/temporary-file-storage/temporary-file-storage.spec.ts @@ -0,0 +1,254 @@ +import { ReadStream, closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { Test, TestingModule } from '@nestjs/testing'; +import { IUser } from '@lumieducation/h5p-server'; +import { Readable } from 'node:stream'; +import { TemporaryFileStorage } from './temporary-file-storage'; +import { TemporaryFile } from './temporary-file'; + +const testContent = 'This is fake H5P content.'; +const today = new Date(); +const tomorrow = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1); + +describe('TemporaryFileStorage', () => { + let module: TestingModule; + let service: TemporaryFileStorage; + const path = '/tmp/test_temp_file_storage'; + + beforeAll(async () => { + if (existsSync(path)) { + rmSync(path, { recursive: true }); + } + mkdirSync(path); + module = await Test.createTestingModule({ + providers: [ + { + provide: TemporaryFileStorage, + useValue: new TemporaryFileStorage(path), + }, + ], + }).compile(); + service = module.get(TemporaryFileStorage); + }); + + afterAll(async () => { + await module.close(); + rmSync(path, { recursive: true }); + }); + + afterEach(() => { + jest.resetAllMocks(); + }); + + const createDummyFile = (filename: string, userId: string) => { + const filepath = join(path, userId, filename); + const dir = dirname(filepath); + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true }); + } + + const file = openSync(filepath, 'w'); + writeSync(file, Buffer.from(testContent)); + closeSync(file); + + const fileMeta = openSync(`${filepath}.meta`, 'w'); + const meta = new TemporaryFile(filename, userId, tomorrow); + writeSync(fileMeta, Buffer.from(JSON.stringify(meta))); + closeSync(fileMeta); + }; + + const setup = () => { + const user: Required = { + email: 'testuser@example.org', + id: '12342-43212', + name: 'Marla Mathe', + type: 'local', + canCreateRestricted: false, + canInstallRecommended: false, + canUpdateAndInstallLibraries: false, + }; + const filename = 'abc/def.txt'; + const filepath = join(path, user.id, filename); + const otherUserId = '32142-32143'; + createDummyFile(filename, user.id); + createDummyFile(filename, otherUserId); + return { + user, + otherUserId, + filename, + filepath, + }; + }; + + it('service should be defined', () => { + expect(service).toBeDefined(); + }); + + describe('sanitizeFilename is called', () => { + describe('WHEN filename is valid', () => { + it('should return same filename', () => { + const filename = 'abc/def-ghi_jkl.txt'; + if (service.sanitizeFilename) { + expect(service.sanitizeFilename(filename)).toBe(filename); + } + }); + }); + describe('WHEN filename contains invalid characters', () => { + it('should sanitize %', () => { + if (service.sanitizeFilename) { + expect(service.sanitizeFilename('abc%/%def%.txt')).not.toContain('%'); + } + }); + it('should sanitize µ', () => { + if (service.sanitizeFilename) { + expect(service.sanitizeFilename('gedµfwa/abc.txt')).not.toContain('µ'); + } + }); + it('should crash if filename contains ..', () => { + expect(() => { + if (service.sanitizeFilename) { + return service.sanitizeFilename('../etc/shadow'); + } + return null; + }).toThrow(); + }); + }); + describe('WHEN filename is empty', () => { + it('should crash', () => { + expect(() => { + if (service.sanitizeFilename) { + service.sanitizeFilename(''); + } + }).toThrow(); + }); + }); + }); + + describe('deleteFile is called', () => { + describe('WHEN file exists', () => { + it('should delete file', async () => { + const { user, filename, filepath } = setup(); + await service.deleteFile(filename, user.id); + const fileExists = existsSync(filepath); + expect(fileExists).toBe(false); + }); + }); + describe('WHEN file does not exist', () => { + it('should throw error', async () => { + const { user } = setup(); + await expect(async () => { + await service.deleteFile('abc/nonexistingfile.txt', user.id); + }).rejects.toThrow(); + }); + }); + }); + + describe('fileExists is called', () => { + describe('WHEN file exists', () => { + it('should return true', async () => { + const { user, filename } = setup(); + await expect(service.fileExists(filename, user)).resolves.toBe(true); + }); + }); + describe('WHEN file does not exist', () => { + it('should return false', async () => { + const { user } = setup(); + await expect(service.fileExists('abc/nonexistingfile.txt', user)).resolves.toBe(false); + }); + }); + }); + + describe('getFileStats is called', () => { + describe('WHEN file exists', () => { + it('should return file stats', async () => { + const { user, filename } = setup(); + const filestats = await service.getFileStats(filename, user); + expect('size' in filestats && 'birthtime' in filestats).toBe(true); + }); + }); + describe('WHEN file does not exist', () => { + it('should throw error', async () => { + const { user } = setup(); + await expect(async () => service.getFileStats('abc/nonexistingfile.txt', user)).rejects.toThrow(); + }); + }); + }); + + describe('getFileStream is called', () => { + describe('WHEN file exists and no range is given', () => { + it('should return readable file stream', async () => { + const { user, filename } = setup(); + const stream = await service.getFileStream(filename, user); + let content = Buffer.alloc(0); + await new Promise((resolve, reject) => { + stream.on('data', (chunk) => { + content += chunk; + }); + stream.on('error', reject); + stream.on('end', resolve); + }); + expect(content).not.toBe(null); + expect(content.toString()).toEqual(testContent); + }); + }); + describe('WHEN file does not exist', () => { + it('should throw error', async () => { + const { user } = setup(); + await expect(async () => service.getFileStream('abc/nonexistingfile.txt', user)).rejects.toThrow(); + }); + }); + }); + + describe('listFiles is called', () => { + describe('WHEN existing user is given', () => { + it('should return only users file', async () => { + const { user, filename } = setup(); + const files = await service.listFiles(user); + expect(files.length).toBe(1); + expect(files[0].ownedByUserId).toBe(user.id); + expect(files[0].filename).toBe(filename); + }); + }); + describe('WHEN no user is given', () => { + it('should return both users files', async () => { + const { user, otherUserId } = setup(); + const files = await service.listFiles(); + expect(files.length).toBe(2); + expect(files[0].ownedByUserId).toBe(user.id); + expect(files[1].ownedByUserId).toBe(otherUserId); + }); + }); + }); + + describe('saveFile is called', () => { + describe('WHEN file exists', () => { + it('should overwrite file', async () => { + const { user, filename } = setup(); + const newData = 'This is new fake H5P content.'; + const readStream = Readable.from(newData); + await service.saveFile(filename, readStream as ReadStream, user, tomorrow); + const savedData = readFileSync(join(path, user.id, filename)); + expect(savedData.toString()).toBe(newData); + }); + }); + describe('WHEN file does not exist', () => { + it('should create new file', async () => { + const { user } = setup(); + const filename = 'newfile.txt'; + const readStream = Readable.from(testContent); + await service.saveFile(filename, readStream as ReadStream, user, tomorrow); + const savedData = readFileSync(join(path, user.id, filename)); + expect(savedData.toString()).toBe(testContent); + }); + }); + describe('WHEN expirationTime is in the past', () => { + it('should throw error', async () => { + const { user, filename } = setup(); + const readStream = Readable.from(testContent); + await expect(async () => + service.saveFile(filename, readStream as ReadStream, user, new Date(2023, 0, 1)) + ).rejects.toThrow(); + }); + }); + }); +}); diff --git a/apps/server/src/modules/h5p-editor/temporary-file-storage/temporary-file-storage.ts b/apps/server/src/modules/h5p-editor/temporary-file-storage/temporary-file-storage.ts new file mode 100644 index 00000000000..d87dfb3347a --- /dev/null +++ b/apps/server/src/modules/h5p-editor/temporary-file-storage/temporary-file-storage.ts @@ -0,0 +1,165 @@ +/* eslint-disable no-await-in-loop */ +// needed for listFiles() +import { ReadStream } from 'fs'; +import { Readable } from 'stream'; +import { mkdirSync } from 'node:fs'; +import { readFile, writeFile, access, mkdir, open, readdir, stat, rm, rmdir } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; +import { relative } from 'path'; +import { Injectable } from '@nestjs/common'; +import { ITemporaryFile, ITemporaryFileStorage, IUser } from '@lumieducation/h5p-server'; +import { FileStats } from './file-stats'; +import { TemporaryFile } from './temporary-file'; + +@Injectable() +export class TemporaryFileStorage implements ITemporaryFileStorage { + constructor(private readonly path: string) { + mkdirSync(path, { recursive: true }); + } + + private checkFilename(filename: string): void { + if (/^[a-zA-Z0-9/._-]+$/g.test(filename) && !filename.includes('..') && !filename.startsWith('/')) { + return; + } + throw new Error(`Filename contains forbidden characters or is empty: '${filename}'`); + } + + private async *readdirFilesRecursive(dirpath: string): AsyncGenerator { + const direntries = await readdir(dirpath, { withFileTypes: true }); + for (const entry of direntries) { + const entrypath = join(dirpath, entry.name); + if (entry.isDirectory()) { + yield* this.readdirFilesRecursive(entrypath); + } else { + yield entrypath; + } + } + } + + private async getFileInfo(filename: string, userId: string): Promise { + this.checkFilename(filename); + this.checkFilename(userId); + const path = `${join(this.path, userId, filename)}.meta`; + const data = await readFile(path); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const tempFileMetadata: TemporaryFile = JSON.parse(data.toString()); + return tempFileMetadata; + } + + private async ensureDirExists(path: string) { + const parent = dirname(path); + if (parent && parent !== '/') { + await this.ensureDirExists(parent); + } + try { + await access(path); + } catch { + // TODO use correct error + await mkdir(path); + } + } + + public sanitizeFilename?(filename: string): string { + const sanitizedFilename = filename.replace(/[^a-zA-Z0-9/._-]/g, '_'); + this.checkFilename(sanitizedFilename); + return sanitizedFilename; + } + + public async deleteFile(filename: string, userId: string): Promise { + this.checkFilename(filename); + this.checkFilename(userId); + const filepath = join(this.path, userId, filename); + await rm(filepath); + await rm(`${filepath}.meta`); + const dir = dirname(filename); + if (dir !== '') { + const dirpath = join(this.path, userId, dir); + if ((await readdir(join(this.path, userId, dir))).length === 0) { + await rmdir(dirpath); + } + } + } + + public async fileExists(filename: string, user: IUser): Promise { + this.checkFilename(filename); + this.checkFilename(user.id); + try { + await access(join(this.path, user.id, filename)); + } catch (error) { + return false; + } + return true; + } + + public async getFileStats(filename: string, user: IUser): Promise { + this.checkFilename(filename); + this.checkFilename(user.id); + const stats = await stat(join(this.path, user.id, filename)); + return new FileStats(stats.birthtime, stats.size); + } + + public async getFileStream( + filename: string, + user: IUser, + rangeStart?: number | undefined, + rangeEnd?: number | undefined + ): Promise { + this.checkFilename(filename); + this.checkFilename(user.id); + const file = await open(join(this.path, user.id, filename)); // file is auto closed + const stream = file.createReadStream({ + start: rangeStart, + end: rangeEnd, + }); + return stream; + } + + public async listFiles(user?: IUser | undefined): Promise { + if (user) { + this.checkFilename(user.id); + await access(join(this.path, user.id)); + } + const users: Array = user ? [user.id] : await readdir(this.path); + const tempFiles: Array = []; + for (const currentUser of users) { + // no-await-in-loop es-lint check disabled here + // user by user should be okay here, otherwise there could be thousands of promises at once + // list ALL files is only needed for clean up job + const userpath = join(this.path, currentUser); + const userFiles: string[] = []; + for await (const file of this.readdirFilesRecursive(join(this.path, currentUser))) { + userFiles.push(relative(userpath, file)); + } + const newTempFiles = await Promise.all( + userFiles + .filter((userFile) => !userFile.endsWith('.meta')) + .map(async (userFile) => this.getFileInfo(userFile, currentUser)) + ); + tempFiles.push(...newTempFiles); + } + return tempFiles; + } + + public async saveFile( + filename: string, + dataStream: ReadStream, + user: IUser, + expirationTime: Date + ): Promise { + this.checkFilename(filename); + this.checkFilename(user.id); + const now = new Date(); + if (expirationTime < now) { + throw new Error('expirationTime must be in the future'); + } + + const path = join(this.path, user.id, filename); + await this.ensureDirExists(dirname(path)); + + await writeFile(path, dataStream); + const meta = new TemporaryFile(filename, user.id, expirationTime); + await writeFile(`${path}.meta`, JSON.stringify(meta)); + + return meta; + } +} diff --git a/apps/server/src/modules/h5p-editor/temporary-file-storage/temporary-file.ts b/apps/server/src/modules/h5p-editor/temporary-file-storage/temporary-file.ts new file mode 100644 index 00000000000..fabbcbd2156 --- /dev/null +++ b/apps/server/src/modules/h5p-editor/temporary-file-storage/temporary-file.ts @@ -0,0 +1,24 @@ +import { ITemporaryFile } from '@lumieducation/h5p-server'; + +export class TemporaryFile implements ITemporaryFile { + /** + * Indicates when the temporary file should be deleted. + */ + expiresAt: Date; + + /** + * The name by which the file can be identified; can be a path including subdirectories (e.g. 'images/xyz.png') + */ + filename: string; + + /** + * The user who is allowed to access the file + */ + ownedByUserId: string; + + constructor(filename: string, ownedByUserId: string, expiresAt: Date) { + this.filename = filename; + this.ownedByUserId = ownedByUserId; + this.expiresAt = expiresAt; + } +} diff --git a/config/default.schema.json b/config/default.schema.json index 584db4a9c9c..92e12a44535 100644 --- a/config/default.schema.json +++ b/config/default.schema.json @@ -301,6 +301,19 @@ } } }, + "H5P_EDITOR": { + "type": "object", + "description": "Properties of the H5P server microservice", + "default": {}, + "properties": { + "INCOMING_REQUEST_TIMEOUT": { + "type": "integer", + "minimum": 0, + "default": 10000, + "description": "Timeout for incoming requests to the h5p editor in milliseconds." + } + } + }, "FEATURE_FWU_CONTENT_ENABLED": { "type": "boolean", "default": false, From c2c78dbb4865360f7a0ec43d5b74712d9f6c4d76 Mon Sep 17 00:00:00 2001 From: Stephan Krause <101647440+SteKrause@users.noreply.github.com> Date: Wed, 7 Jun 2023 11:38:12 +0200 Subject: [PATCH 002/134] THR-2 local content storage (#4140) * Created H5P microservice * Add kubernetes files for h5p microservice * Added @lumieducation/h5p-server package * add ContentStorage with interface IContentStorage * add addContent() * implement addFile(), contentExists(), deleteContent() * implement deleteFile(), fileExists() * add getFileStats(), getFileStream() * add getMetadata(), getParameters(), getUsage() * add getUserPermissions(), listContent() * add listFiles(), sanitizeFilename() * refactor sanitizeFileneame * add user check for getMetadata and getParameters * fix existsOrCreateDir * fix deleteContent and fileExists * fix fileExists and contentExists, refactor methods * add unit tests for contentStorage * delete comments in addFile * fix addFile test and change descriptions * fix getUsage * fix getUsage test * delete TODO * add error message to contentExists + tests * add test for empty contentId at fileEsists * remove unused private sanitize method * adjust errorhandling + add tests for error cases * add tests and fix error cases * replace math.random * change regex in checkfilename * refactor tests and content storage implementation * change any values to unknown * fix create content id * refactor and fix exist boolean in createContentId * fix test can not createContentId * create folder if content will be created * Allow files in subdirectories --------- Co-authored-by: Marvin Rode Co-authored-by: Marvin Rode (Cap) <127723478+marode-cap@users.noreply.github.com> --- .../contentStorage/contentStorage.spec.ts | 472 ++++++++++++++++++ .../contentStorage/contentStorage.ts | 295 +++++++++++ 2 files changed, 767 insertions(+) create mode 100644 apps/server/src/modules/h5p-editor/contentStorage/contentStorage.spec.ts create mode 100644 apps/server/src/modules/h5p-editor/contentStorage/contentStorage.ts diff --git a/apps/server/src/modules/h5p-editor/contentStorage/contentStorage.spec.ts b/apps/server/src/modules/h5p-editor/contentStorage/contentStorage.spec.ts new file mode 100644 index 00000000000..5da9c01dfd1 --- /dev/null +++ b/apps/server/src/modules/h5p-editor/contentStorage/contentStorage.spec.ts @@ -0,0 +1,472 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { IContentMetadata, ILibraryName, IUser } from '@lumieducation/h5p-server'; +import * as fs from 'node:fs'; +import fsPromiseMock from 'node:fs/promises'; +import { Readable, Stream } from 'stream'; +import rimraf from 'rimraf'; +import path from 'node:path'; +import { ContentStorage } from './contentStorage'; + +function delay(ms: number) { + // eslint-disable-next-line no-promise-executor-return + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +const setup = () => { + const dir = './apps/server/src/modules/h5p-editor/contentStorage/testContentStorage/'; + + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir); + } + + const library: ILibraryName = { + machineName: 'testLibrary', + majorVersion: 1, + minorVersion: 0, + }; + + const library2: ILibraryName = { + machineName: 'testLibrary56', + majorVersion: 1, + minorVersion: 0, + }; + + const metadata: IContentMetadata = { + embedTypes: ['div'], + language: 'de', + mainLibrary: 'testLibrary', + preloadedDependencies: [library], + editorDependencies: [library], + dynamicDependencies: [library], + defaultLanguage: '', + license: '', + title: 'Test123', + }; + + const metadata2: IContentMetadata = { + embedTypes: ['div'], + language: 'de', + mainLibrary: 'testLibrary2', + preloadedDependencies: [library], + defaultLanguage: '', + license: '', + title: 'Test123', + }; + + const metadata3: IContentMetadata = { + embedTypes: ['div'], + language: 'de', + mainLibrary: 'testLibrary3', + preloadedDependencies: [], + editorDependencies: [], + dynamicDependencies: [], + defaultLanguage: '', + license: '', + title: 'Test123', + }; + + const testContentFilename = 'testContent.json'; + fs.writeFileSync(path.join(dir, testContentFilename), JSON.stringify(metadata)); + const content = testContentFilename; + const user: IUser = { + canCreateRestricted: false, + canInstallRecommended: false, + canUpdateAndInstallLibraries: false, + email: 'testUser1@testUser123.de', + id: '', + name: 'User Test', + type: '', + }; + const stream: Stream = new Stream(); + + const contentId = '2345'; + const contentId2 = '6789'; + const contentId4 = '5678906'; + const notExistingContentId = '987mn'; + fs.mkdirSync(path.join(dir, contentId.toString()), { recursive: true }); + fs.writeFileSync(path.join(dir, contentId.toString(), 'h5p.json'), JSON.stringify(metadata)); + fs.writeFileSync(path.join(dir, contentId.toString(), 'content.json'), JSON.stringify(content)); + + fs.mkdirSync(path.join(dir, contentId2), { recursive: true }); + fs.writeFileSync(path.join(dir, contentId2.toString(), 'h5p.json'), JSON.stringify(metadata2)); + fs.writeFileSync(path.join(dir, contentId2.toString(), 'content.json'), JSON.stringify(content)); + + fs.mkdirSync(path.join(dir, contentId4), { recursive: true }); + fs.writeFileSync(path.join(dir, contentId4.toString(), 'h5p.json'), JSON.stringify(metadata3)); + fs.writeFileSync(path.join(dir, contentId4.toString(), 'content.json'), JSON.stringify(content)); + + const filename1 = 'testFile1.json'; + const notExistingFilename = 'testFile987.json'; + const undefinedContentId = ''; + const wrongFilename = 'testName!?.json'; + const filename2 = 'testFiletoAdd123.json'; + const emptyContentId = ''; + fs.writeFileSync(path.join(dir, contentId.toString(), filename1), JSON.stringify(content)); + + return { + content, + contentId, + contentId2, + dir, + emptyContentId, + filename1, + filename2, + library, + library2, + metadata, + notExistingContentId, + notExistingFilename, + stream, + undefinedContentId, + user, + wrongFilename, + }; +}; + +describe('ContentStorage', () => { + let module: TestingModule; + let service: ContentStorage; + const { dir } = setup(); + + beforeAll(async () => { + module = await Test.createTestingModule({ + providers: [ + { + provide: ContentStorage, + useValue: new ContentStorage(dir, { invalidCharactersRegexp: /!/ }), + }, + ], + }).compile(); + service = module.get(ContentStorage); + }); + + afterAll(async () => { + await module.close(); + }); + + afterEach(() => { + rimraf.sync(dir); + jest.resetAllMocks(); + }); + + it('should be defined', () => { + expect(service).toBeDefined(); + }); + + describe('addContent', () => { + describe('WHEN content is created successfully', () => { + it('should return contentId', async () => { + const { metadata, content, user } = setup(); + const contentID = await service.addContent(metadata, content, user); + expect(contentID).toBeDefined(); + expect(typeof contentID).toBe('string'); + }); + }); + describe('WHEN contentId is empty', () => { + it('should throw new error', async () => { + const { metadata, content, user, emptyContentId } = setup(); + try { + await service.addContent(metadata, content, user, emptyContentId); + } catch (err) { + expect(err).toBeInstanceOf(Error); + } + }); + }); + describe('WHEN content can not be added error', () => { + it('should throw new error', async () => { + const { metadata, content, user } = setup(); + jest.spyOn(fsPromiseMock, 'writeFile').mockImplementationOnce(() => { + throw new Error('Could not write file'); + }); + try { + await service.addContent(metadata, content, user); + } catch (err) { + expect(err).toBeInstanceOf(Error); + } + }); + }); + describe('WHEN contentId can not be generated', () => { + it('should throw new error', async () => { + const { metadata, content, user } = setup(); + // eslint-disable-next-line @typescript-eslint/require-await + jest.spyOn(fsPromiseMock, 'access').mockImplementation(async () => undefined); + try { + await service.addContent(metadata, content, user); + } catch (err) { + expect(err).toBeInstanceOf(Error); + } + }); + }); + }); + + describe('addFile', () => { + describe('WHEN file is created successfully', () => { + it('should add a file to content', async () => { + const { stream, contentId } = setup(); + const filename = 'testFiletoAdd123.json'; + await service.addFile(contentId, filename, stream); + await delay(0); + const fileExists = fs.existsSync(path.join(dir, contentId.toString(), filename)); + expect(fileExists).toEqual(true); + }); + }); + describe('WHEN file is not created successfully', () => { + it('should throw an error', async () => { + const { stream, notExistingContentId, filename2 } = setup(); + try { + await service.addFile(notExistingContentId, filename2, stream); + } catch (err) { + expect(err).toBeInstanceOf(Error); + } + }); + }); + describe('WHEN filename has special characters', () => { + it('should throw an error', async () => { + const { stream, notExistingContentId, wrongFilename } = setup(); + try { + await service.addFile(notExistingContentId, wrongFilename, stream); + } catch (err) { + expect(err).toBeInstanceOf(Error); + } + }); + }); + }); + + describe('contentExists', () => { + describe('WHEN content exists', () => { + it('should return true', async () => { + const { contentId } = setup(); + const contentExists = await service.contentExists(contentId); + expect(contentExists).toEqual(true); + }); + }); + describe('WHEN content does not exist', () => { + it('should return false', async () => { + const { notExistingContentId } = setup(); + const contentExists = await service.contentExists(notExistingContentId); + expect(contentExists).toEqual(false); + }); + }); + describe('WHEN content is undefined', () => { + it('should throw an error', async () => { + const { undefinedContentId } = setup(); + try { + await service.contentExists(undefinedContentId); + } catch (err) { + expect(err).toBeInstanceOf(Error); + } + }); + }); + }); + + describe('deleteContent', () => { + describe('WHEN content is deleted successfully', () => { + it('should delete existing content', async () => { + const { contentId } = setup(); + await service.deleteContent(contentId); + const contentExists = fs.existsSync(path.join(dir, contentId.toString())); + expect(contentExists).toEqual(false); + }); + }); + + describe('WHEN content can not be deleted', () => { + it('should throw error', async () => { + const { notExistingContentId } = setup(); + try { + await service.deleteContent(notExistingContentId); + } catch (err) { + expect(err).toBeInstanceOf(Error); + } + }); + }); + }); + describe('deleteFile', () => { + describe('WHEN file is deleted successfully', () => { + it('should delete existing file', async () => { + const { contentId, filename1 } = setup(); + await service.deleteFile(contentId, filename1); + const fileExists = fs.existsSync(path.join(dir, contentId.toString(), filename1)); + expect(fileExists).toEqual(false); + }); + }); + + describe('WHEN file can not be deleted', () => { + it('should throw error', async () => { + const { notExistingContentId, notExistingFilename } = setup(); + try { + await service.deleteFile(notExistingContentId, notExistingFilename); + } catch (err) { + expect(err).toBeInstanceOf(Error); + } + }); + }); + }); + describe('fileExists', () => { + describe('WHEN file exists', () => { + it('should return true', async () => { + const { contentId, filename1 } = setup(); + const fileExists = await service.fileExists(contentId, filename1); + expect(fileExists).toEqual(true); + }); + }); + + describe('WHEN file does not exist', () => { + it('should return false', async () => { + const { notExistingContentId, notExistingFilename } = setup(); + const fileExists = await service.fileExists(notExistingContentId, notExistingFilename); + expect(fileExists).toEqual(false); + }); + }); + describe('WHEN conetntId is undefined', () => { + it('should throw an error', async () => { + const { undefinedContentId, notExistingFilename } = setup(); + try { + await service.fileExists(undefinedContentId, notExistingFilename); + } catch (err) { + expect(err).toBeInstanceOf(Error); + } + }); + }); + }); + + describe('getFileStats', () => { + describe('WHEN file exists', () => { + it('should return fileStats', async () => { + const { contentId, filename1, user } = setup(); + const fileStats = await service.getFileStats(contentId, filename1, user); + expect(fileStats).toBeDefined(); + expect(typeof fileStats).toBe('object'); + expect(fileStats.size).toBeGreaterThan(0); + expect(fileStats.birthtime).toBeDefined(); + }); + }); + + describe('WHEN file does not exist', () => { + it('should throw an error', async () => { + const { notExistingContentId, notExistingFilename, user } = setup(); + try { + await service.getFileStats(notExistingContentId, notExistingFilename, user); + } catch (err) { + expect(err).toBeInstanceOf(Error); + } + }); + }); + }); + + describe('getFileStream', () => { + describe('WHEN file exists', () => { + it('should return fileStream', async () => { + const { contentId, filename1, user } = setup(); + const fileStream = await service.getFileStream(contentId, filename1, user); + expect(fileStream).toBeDefined(); + expect(typeof fileStream).toBe('object'); + expect(fileStream).toBeInstanceOf(Readable); + }); + }); + + describe('WHEN file does not exist', () => { + it('should throw an error', async () => { + const { notExistingContentId, notExistingFilename, user } = setup(); + try { + await service.getFileStream(notExistingContentId, notExistingFilename, user); + } catch (err) { + expect(err).toBeInstanceOf(Error); + } + }); + }); + }); + + describe('getMetadata', () => { + describe('WHEN file exists', () => { + it('should return metadata', async () => { + const { contentId, user } = setup(); + const metadata = await service.getMetadata(contentId, user); + expect(metadata).toBeDefined(); + expect(metadata.language).toEqual('de'); + }); + }); + + describe('WHEN user is not defined', () => { + it('should throw an error', async () => { + const { contentId } = setup(); + try { + await service.getMetadata(contentId); + } catch (err) { + expect(err).toBeInstanceOf(Error); + } + }); + }); + }); + + describe('getParameters', () => { + describe('WHEN user and content is defined', () => { + it('should return parameters', async () => { + const { contentId, user } = setup(); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const parameters = await service.getParameters(contentId, user); + expect(parameters).toBeDefined(); + expect(typeof parameters).toBe('string'); + }); + }); + + describe('WHEN user is not defined', () => { + it('should throw an error', async () => { + const { contentId } = setup(); + try { + await service.getParameters(contentId); + } catch (err) { + expect(err).toBeInstanceOf(Error); + } + }); + }); + }); + + describe('getUsage', () => { + describe('WHEN file exists and has main library', () => { + it('should return usage with main library greater than 0', async () => { + const { library } = setup(); + const usage = await service.getUsage(library); + expect(usage).toBeDefined(); + expect(usage.asMainLibrary).toBeGreaterThan(0); + expect(usage.asDependency).toBeGreaterThan(0); + }); + }); + describe('WHEN file exists and does not have a library', () => { + it('should return 0 dependecies and libaries', async () => { + const { library2 } = setup(); + const usage = await service.getUsage(library2); + expect(usage).toBeDefined(); + expect(usage.asMainLibrary).toEqual(0); + expect(usage.asDependency).toEqual(0); + }); + }); + }); + + describe('getUserPermissions', () => { + describe('WHEN user and content is defined', () => { + it('should return parameters', async () => { + const { contentId, user } = setup(); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const permissions = await service.getUserPermissions(contentId, user); + expect(permissions).toBeDefined(); + expect(permissions.length).toBeGreaterThan(0); + expect(permissions[1]).toEqual(1); + expect(permissions[2]).toEqual(2); + expect(permissions[3]).toEqual(3); + expect(permissions[4]).toEqual(5); + }); + }); + }); + + describe('listFiles', () => { + describe('WHEN content has files', () => { + it('should return a list of files from the content', async () => { + const { contentId, user } = setup(); + const fileList = await service.listFiles(contentId, user); + expect(fileList).toBeDefined(); + expect(fileList.length).toBeGreaterThan(0); + expect(fileList[0]).toEqual('testFile1.json'); + }); + }); + }); +}); diff --git a/apps/server/src/modules/h5p-editor/contentStorage/contentStorage.ts b/apps/server/src/modules/h5p-editor/contentStorage/contentStorage.ts new file mode 100644 index 00000000000..c948f3588ad --- /dev/null +++ b/apps/server/src/modules/h5p-editor/contentStorage/contentStorage.ts @@ -0,0 +1,295 @@ +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { Injectable } from '@nestjs/common'; +import { Readable, Stream } from 'stream'; +import * as fs from 'node:fs'; +import * as fsPromises from 'node:fs/promises'; +import { getAllFiles } from 'get-all-files'; +import { + ContentId, + IContentMetadata, + IContentStorage, + LibraryName, + IFileStats, + ILibraryName, + IUser, + Permission, + streamToString, +} from '@lumieducation/h5p-server'; +import path from 'path'; +import rimraf from 'rimraf'; + +@Injectable() +export class ContentStorage implements IContentStorage { + constructor( + protected contentPath: string, + protected options?: { + invalidCharactersRegexp?: RegExp; + maxPathLength?: number; + } + ) {} + + public async addContent( + metadata: IContentMetadata, + content: unknown, + user: IUser, + contentId?: ContentId | undefined + ): Promise { + if (contentId === null || contentId === undefined) { + contentId = await this.createContentId(); + } + try { + fs.existsSync(path.join(this.getContentPath(), contentId.toString())); + await this.existsOrCreateDir(contentId); + await fsPromises.writeFile( + path.join(this.getContentPath(), contentId.toString(), 'h5p.json'), + JSON.stringify(metadata) + ); + await fsPromises.writeFile( + path.join(this.getContentPath(), contentId.toString(), 'content.json'), + JSON.stringify(content) + ); + } catch (error) { + if (fs.existsSync(path.join(this.getContentPath(), contentId.toString()))) { + rimraf.sync(path.join(this.getContentPath(), contentId.toString())); + } + + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call + throw new Error(`Error creating content.${error.toString()}`); + } + return contentId; + } + + // eslint-disable-next-line @typescript-eslint/require-await + public async addFile(contentId: string, filename: string, stream: Stream, user?: IUser | undefined): Promise { + this.checkFilename(filename); + if (!fs.existsSync(path.join(this.getContentPath(), contentId.toString()))) { + throw new Error('404: Content not Found at addFile.'); + } + + await this.existsOrCreateDir(contentId, path.dirname(filename)); + const fullPath = path.join(this.getContentPath(), contentId.toString(), filename); + const writeStream = fs.createWriteStream(fullPath); + stream.pipe(writeStream); + } + + public contentExists(contentId: string): Promise { + if (contentId === '' || contentId === undefined) { + throw new Error('ContentId is empty or undefined.'); + } + const exist = fs.existsSync(path.join(this.getContentPath(), contentId.toString())); + const existPromise: Promise = >(exist); + return existPromise; + } + + public async deleteContent(contentId: string, user?: IUser | undefined): Promise { + const fullPath = path.join(this.getContentPath(), contentId.toString()); + try { + if (!fs.existsSync(fullPath)) { + throw new Error('404: Content not Found at deleteContent.'); + } + fs.readdirSync(fullPath).forEach((file, index) => { + const curPath = path.join(fullPath, file); + fs.unlinkSync(curPath); + }); + + await fsPromises.rmdir(path.join(this.getContentPath(), contentId.toString())); + } catch (error) { + if (error) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call + throw new Error(error.toString()); + } + } + } + + public async deleteFile(contentId: string, filename: string, user?: IUser | undefined): Promise { + this.checkFilename(filename); + const absolutePath = path.join(this.getContentPath(), contentId.toString(), filename); + const exist = fs.existsSync(absolutePath); + if (!exist) { + throw new Error('404: Content not Found at deleteFile.'); + } + await fsPromises.rm(absolutePath); + } + + public fileExists(contentId: string, filename: string): Promise { + this.checkFilename(filename); + if (contentId === '' || contentId === undefined) { + throw new Error('ContentId is empty or undefined.'); + } + const exist = fs.existsSync(path.join(this.getContentPath(), contentId.toString(), filename)); + const existPromise: Promise = >(exist); + return existPromise; + } + + public async getFileStats(contentId: string, file: string, user: IUser): Promise { + if (!(await this.fileExists(contentId, file))) { + throw new Error('404: Content does not found to get file stats.'); + } + const fileStats = await fsPromises.stat(path.join(this.getContentPath(), contentId.toString(), file)); + return fileStats; + } + + public getFileStream( + contentId: string, + file: string, + user: IUser, + rangeStart?: number | undefined, + rangeEnd?: number | undefined + ): Promise { + const exist = (this.fileExists(contentId, file)); + if (!exist) { + throw new Error('404: Content file missing.'); + } + return >(fs.createReadStream( + path.join(this.getContentPath(), contentId.toString(), file), + { + start: rangeStart, + end: rangeEnd, + } + )); + } + + public async getMetadata(contentId: string, user?: IUser | undefined): Promise { + if (user !== undefined && user !== null) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return JSON.parse(await streamToString(await this.getFileStream(contentId, 'h5p.json', user))); + } + throw new Error('Could not get Metadata'); + } + + public async getParameters(contentId: string, user?: IUser | undefined): Promise { + if (user !== undefined && user !== null) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return JSON.parse(await streamToString(await this.getFileStream(contentId, 'content.json', user))); + } + throw new Error('Could not get Parameters'); + } + + public async getUsage(library: ILibraryName): Promise<{ asDependency: number; asMainLibrary: number }> { + let asDependency = 0; + let asMainLibrary = 0; + const defaultUser: IUser = { + canCreateRestricted: false, + canInstallRecommended: false, + canUpdateAndInstallLibraries: false, + email: '', + id: '', + name: 'getUsage', + type: '', + }; + + const contentIds = await this.listContent(); + for (const contentId of contentIds) { + // eslint-disable-next-line no-await-in-loop + const contentMetadata = await this.getMetadata(contentId, defaultUser); + const isMainLibrary = contentMetadata.mainLibrary === library.machineName; + if (this.hasDependencyOn(contentMetadata, library)) { + if (isMainLibrary) { + asMainLibrary += 1; + } else { + asDependency += 1; + } + } + } + return { asDependency, asMainLibrary }; + } + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + public getUserPermissions(contentId: string, user: IUser): Promise { + const permission = >( + ([Permission.Delete, Permission.Download, Permission.Edit, Permission.Embed, Permission.View]) + ); + return permission; + } + + public async listContent(user?: IUser | undefined): Promise { + const directories = await fsPromises.readdir(this.getContentPath()); + return ( + await Promise.all( + directories.map(async (dir) => { + if ( + !(await (>(fs.existsSync(path.join(this.getContentPath(), dir, 'h5p.json'))))) + ) { + return ''; + } + return dir; + }) + ) + ).filter((content) => content !== ''); + } + + public async listFiles(contentId: string, user: IUser): Promise { + const contentDirectoryPath = path.join(this.getContentPath(), contentId.toString()); + const contentDirectoryPathLength = contentDirectoryPath.length + 1; + const absolutePaths = await getAllFiles(path.join(contentDirectoryPath)).toArray(); + const contentPath = path.join(contentDirectoryPath, 'content.json'); + const h5pPath = path.join(contentDirectoryPath, 'h5p.json'); + return absolutePaths + .filter((p) => p !== contentPath && p !== h5pPath) + .map((p) => p.substring(contentDirectoryPathLength)); + } + + // private methods + + protected async createContentId() { + let counter = 0; + let id = 0; + let exist = true; + do { + id = ContentStorage.getRandomId(1, 2 ** 32); + counter += 1; + const p = path.join(this.getContentPath(), id.toString()); + try { + // eslint-disable-next-line no-await-in-loop + await fsPromises.access(p); + } catch (error) { + exist = false; + } + } while (exist && counter < 10); + if (exist && counter === 10) { + throw new Error('Error generating contentId.'); + } + return id.toString(); + } + + private static getRandomId(min: number, max: number): number { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, global-require, @typescript-eslint/no-var-requires + const crypto = require('crypto'); + // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call + return crypto.randomBytes(4).readUInt32BE(0, true); + } + + protected getContentPath(): string { + return this.contentPath; + } + + private async existsOrCreateDir(contentId: ContentId, subdir = '') { + await fsPromises.mkdir(path.join(this.getContentPath(), contentId.toString(), subdir), { recursive: true }); + } + + private hasDependencyOn( + metadata: { + dynamicDependencies?: ILibraryName[]; + editorDependencies?: ILibraryName[]; + preloadedDependencies: ILibraryName[]; + }, + library: ILibraryName + ): boolean { + if ( + metadata.preloadedDependencies.some((dep) => LibraryName.equal(dep, library)) || + metadata.editorDependencies?.some((dep) => LibraryName.equal(dep, library)) || + metadata.dynamicDependencies?.some((dep) => LibraryName.equal(dep, library)) + ) { + return true; + } + return false; + } + + checkFilename(filename: string): void { + filename = filename.split('.').slice(0, -1).join('.'); + if (/^[a-zA-Z0-9/._-]*$/.test(filename) && !filename.includes('..') && !filename.startsWith('/')) { + return; + } + throw new Error(`Filename contains forbidden characters ${filename}`); + } +} From 670941446b3d3607e2e508c1764e3c0eeb6d5fc5 Mon Sep 17 00:00:00 2001 From: "Marvin Rode (Cap)" <127723478+marode-cap@users.noreply.github.com> Date: Wed, 7 Jun 2023 11:38:52 +0200 Subject: [PATCH 003/134] THR-3 local library storage (#4133) * Implemented library storage * Tests for librray storage * full test coverage * Moved files --------- Co-authored-by: Stephan Krause <101647440+SteKrause@users.noreply.github.com> --- .../libraryStorage/libraryStorage.spec.ts | 462 ++++++++++++++++++ .../libraryStorage/libraryStorage.ts | 413 ++++++++++++++++ 2 files changed, 875 insertions(+) create mode 100644 apps/server/src/modules/h5p-editor/libraryStorage/libraryStorage.spec.ts create mode 100644 apps/server/src/modules/h5p-editor/libraryStorage/libraryStorage.ts diff --git a/apps/server/src/modules/h5p-editor/libraryStorage/libraryStorage.spec.ts b/apps/server/src/modules/h5p-editor/libraryStorage/libraryStorage.spec.ts new file mode 100644 index 00000000000..10ee2c0613c --- /dev/null +++ b/apps/server/src/modules/h5p-editor/libraryStorage/libraryStorage.spec.ts @@ -0,0 +1,462 @@ +import { Test, TestingModule } from '@nestjs/testing'; + +import { ILibraryMetadata, ILibraryName } from '@lumieducation/h5p-server'; +import { mkdtemp } from 'fs/promises'; +import fs from 'node:fs/promises'; +import os from 'os'; +import path from 'path'; +import rimraf from 'rimraf'; +import { Readable } from 'stream'; + +import { LibraryStorage } from './libraryStorage'; + +describe('LibraryStorage', () => { + let module: TestingModule; + let adapter: LibraryStorage; + + let tmpDir: string; + + const createTestData = () => { + const createLib = (name: string, major: number, minor: number, patch: number): ILibraryMetadata => { + return { + machineName: name, + majorVersion: major, + minorVersion: minor, + patchVersion: patch, + runnable: false, + title: name, + }; + }; + + const metadataToName = ({ machineName, majorVersion, minorVersion }: ILibraryMetadata): ILibraryName => { + return { + machineName, + majorVersion, + minorVersion, + }; + }; + + const testingLib = createLib('testing', 1, 2, 3); + + const addonLib = createLib('addon', 1, 2, 3); + addonLib.addTo = { player: { machineNames: [testingLib.machineName] } }; + + const circularA = createLib('circular_a', 1, 2, 3); + const circularB = createLib('circular_b', 1, 2, 3); + circularA.preloadedDependencies = [metadataToName(circularB)]; + circularB.editorDependencies = [metadataToName(circularA)]; + + const fakeLibraryName: ILibraryName = { machineName: 'fake', majorVersion: 2, minorVersion: 3 }; + + const testingLibDependentA = createLib('first_dependent', 2, 5, 6); + testingLibDependentA.dynamicDependencies = [metadataToName(testingLib)]; + const testingLibDependentB = createLib('second_dependent', 2, 5, 6); + testingLibDependentB.preloadedDependencies = [metadataToName(testingLib)]; + + const libWithNonExistingDependency = createLib('fake_dependency', 2, 5, 6); + libWithNonExistingDependency.editorDependencies = [fakeLibraryName]; + + return { + libraries: [ + testingLib, + addonLib, + circularA, + circularB, + testingLibDependentA, + testingLibDependentB, + libWithNonExistingDependency, + ], + names: { + testingLib, + addonLib, + fakeLibraryName, + }, + }; + }; + + beforeAll(async () => { + const dir = path.join(os.tmpdir(), 'LibraryStorageTest'); + tmpDir = await mkdtemp(dir); + + module = await Test.createTestingModule({ + providers: [{ provide: LibraryStorage, useValue: new LibraryStorage(tmpDir) }], + }).compile(); + + adapter = module.get(LibraryStorage); + }); + + afterAll(async () => { + await module.close(); + }); + + afterEach(() => { + rimraf.sync(tmpDir); + }); + + it('should be defined', () => { + expect(adapter).toBeDefined(); + }); + + describe('when managing library metadata', () => { + const setup = async (addLibrary = true) => { + const { + names: { testingLib }, + } = createTestData(); + + if (addLibrary) { + await adapter.addLibrary(testingLib, false); + } + + return { testingLib }; + }; + + describe('when adding library', () => { + it('should succeed', async () => { + await setup(); + }); + + it('should fail to override existing library', async () => { + const { testingLib } = await setup(); + + const addLib = adapter.addLibrary(testingLib, false); + await expect(addLib).rejects.toThrowError("Can't add library because it already exists"); + }); + + it('should fail on IO errors', async () => { + const { testingLib } = await setup(false); + + jest.spyOn(fs, 'mkdir').mockImplementationOnce(() => { + throw new Error('Could not create directory'); + }); + + const addLibrary = adapter.addLibrary(testingLib, false); + await expect(addLibrary).rejects.toThrowError('Could not create directory'); + }); + }); + + describe('when getting metadata', () => { + it('should succeed if library existst', async () => { + const { testingLib } = await setup(); + + const returnedLibrary = await adapter.getLibrary(testingLib); + expect(returnedLibrary).toEqual(expect.objectContaining(testingLib)); + }); + + it("should fail if library doesn't exist", async () => { + const { testingLib } = await setup(false); + + const getLibrary = adapter.getLibrary(testingLib); + await expect(getLibrary).rejects.toThrowError('The requested library does not exist'); + }); + }); + + describe('when checking installed status', () => { + it('should return true if library is installed', async () => { + const { testingLib } = await setup(); + + const installed = await adapter.isInstalled(testingLib); + expect(installed).toBe(true); + }); + + it("should return false if library isn't installed", async () => { + const { testingLib } = await setup(false); + + const installed = await adapter.isInstalled(testingLib); + expect(installed).toBe(false); + }); + }); + + describe('when updating metadata', () => { + it('should update metadata', async () => { + const { testingLib } = await setup(); + + testingLib.author = 'Test Author'; + const updatedLibrary = await adapter.updateLibrary(testingLib); + const retrievedLibrary = await adapter.getLibrary(testingLib); + expect(retrievedLibrary).toEqual(updatedLibrary); + }); + + it("should fail if library doesn't exist", async () => { + const { testingLib } = await setup(false); + + const updateLibrary = adapter.updateLibrary(testingLib); + await expect(updateLibrary).rejects.toThrowError('Library is not installed'); + }); + }); + + describe('when updating additional metadata', () => { + it('should return true if data has changed', async () => { + const { testingLib } = await setup(); + + const updated = await adapter.updateAdditionalMetadata(testingLib, { restricted: true }); + expect(updated).toBe(true); + }); + + it("should return false if data hasn't changed", async () => { + const { testingLib } = await setup(); + + const updated = await adapter.updateAdditionalMetadata(testingLib, { restricted: false }); + expect(updated).toBe(false); + }); + + it('should fail if data could not be updated', async () => { + const { testingLib } = await setup(); + + jest.spyOn(fs, 'writeFile').mockImplementationOnce(() => { + throw new Error('Could not write file'); + }); + + const updateMetadata = adapter.updateAdditionalMetadata(testingLib, { restricted: true }); + await expect(updateMetadata).rejects.toThrowError('Could not update metadata'); + }); + }); + + describe('when deleting library', () => { + it('should succeed if library existst', async () => { + const { testingLib } = await setup(); + + await adapter.deleteLibrary(testingLib); + await expect(adapter.getLibrary(testingLib)).rejects.toThrow(); + }); + + it("should fail if library doesn't existst", async () => { + const { testingLib } = await setup(false); + + const deleteLibrary = adapter.deleteLibrary(testingLib); + await expect(deleteLibrary).rejects.toThrowError("Can't delete library, because it is not installed"); + }); + }); + }); + + describe('When getting library dependencies', () => { + const setup = async () => { + const { libraries, names } = createTestData(); + + for await (const library of libraries) { + await adapter.addLibrary(library, false); + } + + return names; + }; + + it('should find addon libraries', async () => { + const { addonLib } = await setup(); + + const addons = await adapter.listAddons(); + expect(addons).toContainEqual(expect.objectContaining(addonLib)); + }); + + it('should count dependencies', async () => { + await setup(); + + const dependencies = await adapter.getAllDependentsCount(); + expect(dependencies).toEqual({ 'circular_a-1.2': 1, 'testing-1.2': 2, 'fake-2.3': 1 }); + }); + + it('should count dependents for single library', async () => { + const { testingLib } = await setup(); + + const count = await adapter.getDependentsCount(testingLib); + expect(count).toBe(2); + }); + + it('should count dependencies for library without dependents', async () => { + const { addonLib } = await setup(); + + const count = await adapter.getDependentsCount(addonLib); + expect(count).toBe(0); + }); + }); + + describe('when listing libraries', () => { + const setup = async () => { + const { + libraries, + names: { testingLib }, + } = createTestData(); + + for await (const library of libraries) { + await adapter.addLibrary(library, false); + } + + return { libraries, testingLib }; + }; + + it('should return all libraries when no filter is used', async () => { + const { libraries } = await setup(); + + const allLibraries = await adapter.getInstalledLibraryNames(); + expect(allLibraries.length).toBe(libraries.length); + }); + + it('should return all libraries with machinename', async () => { + const { testingLib } = await setup(); + + const allLibraries = await adapter.getInstalledLibraryNames(testingLib.machineName); + expect(allLibraries.length).toBe(1); + }); + }); + + describe('when managing files', () => { + const setup = async (addFiles = true) => { + const { + names: { testingLib }, + } = createTestData(); + + const testFile = { + name: 'test/abc.json', + content: JSON.stringify({ property: 'value' }), + }; + + if (addFiles) { + await adapter.addLibrary(testingLib, false); + await adapter.addFile(testingLib, testFile.name, Readable.from(testFile.content)); + } + + return { testingLib, testFile }; + }; + + describe('when adding files', () => { + it('should work', async () => { + await setup(); + }); + + it('should fail if library is not installed', async () => { + const { testingLib, testFile } = await setup(false); + + const addFile = adapter.addFile(testingLib, testFile.name, Readable.from(testFile.content)); + await expect(addFile).rejects.toThrowError('Could not add file to library'); + }); + + it('should fail on illegal filename', async () => { + const { testingLib } = await setup(); + + const filenames = ['../abc.json', '/test/abc.json']; + + await Promise.all( + filenames.map((filename) => { + const addFile = adapter.addFile(testingLib, filename, Readable.from('')); + return expect(addFile).rejects.toThrowError('Illegal filename'); + }) + ); + }); + }); + + it('should list all files', async () => { + const { testingLib, testFile } = await setup(); + + const files = await adapter.listFiles(testingLib); + expect(files).toContainEqual(expect.stringContaining(testFile.name)); + }); + + describe('when checking if file exists', () => { + it('should return true if it exists', async () => { + const { testingLib, testFile } = await setup(); + + const exists = await adapter.fileExists(testingLib, testFile.name); + expect(exists).toBe(true); + }); + + it("should return false if it doesn't exist", async () => { + const { testingLib, testFile } = await setup(false); + + const exists = await adapter.fileExists(testingLib, testFile.name); + expect(exists).toBe(false); + }); + }); + + describe('when clearing files', () => { + it('should remove all files', async () => { + const { testingLib } = await setup(); + + await adapter.clearFiles(testingLib); + const files = await adapter.listFiles(testingLib); + expect(files).toEqual([expect.stringContaining('library.json')]); + }); + + it("should fail if library doesn't exist", async () => { + const { testingLib } = await setup(false); + + const clearFiles = adapter.clearFiles(testingLib); + await expect(clearFiles).rejects.toThrowError("Can't clear library files, because it is not installed"); + }); + }); + + describe('when retrieving files', () => { + it('should return parsed json', async () => { + const { testingLib, testFile } = await setup(); + + const json = await adapter.getFileAsJson(testingLib, testFile.name); + expect(json).toEqual(JSON.parse(testFile.content)); + }); + + it('should return file as string', async () => { + const { testingLib, testFile } = await setup(); + + const fileContent = await adapter.getFileAsString(testingLib, testFile.name); + expect(fileContent).toEqual(testFile.content); + }); + + it('should return file as stream', async () => { + const { testingLib, testFile } = await setup(); + + const fileStream = await adapter.getFileStream(testingLib, testFile.name); + + const streamContents = await new Promise((resolve, reject) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const chunks: any[] = []; + fileStream.on('data', (chunk) => chunks.push(chunk)); + fileStream.on('error', reject); + fileStream.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8'))); + }); + + expect(streamContents).toEqual(testFile.content); + }); + }); + describe('when getting file stats', () => { + it('should return parsed json', async () => { + const { testingLib, testFile } = await setup(); + + const stats = await adapter.getFileStats(testingLib, testFile.name); + + expect(stats).toMatchObject({ + size: expect.any(Number), + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + birthtime: expect.any(Object), // expect.any(Date) behaves incorrectly + }); + }); + + it("should fail if file doesn't exist", async () => { + const { testingLib, testFile } = await setup(false); + + const getStats = adapter.getFileStats(testingLib, testFile.name); + await expect(getStats).rejects.toThrowError('The requested file does not exist'); + }); + }); + }); + + describe('when getting languages', () => { + const setup = async () => { + const { + names: { testingLib }, + } = createTestData(); + + await adapter.addLibrary(testingLib, false); + + const languages = ['en', 'de']; + + await Promise.all( + languages.map((language) => adapter.addFile(testingLib, `language/${language}.json`, Readable.from(''))) + ); + + return { testingLib, languages }; + }; + + it('should return a list of languages', async () => { + const { testingLib, languages } = await setup(); + + const supportedLanguages = await adapter.getLanguages(testingLib); + expect(supportedLanguages).toEqual(expect.arrayContaining(languages)); + }); + }); +}); diff --git a/apps/server/src/modules/h5p-editor/libraryStorage/libraryStorage.ts b/apps/server/src/modules/h5p-editor/libraryStorage/libraryStorage.ts new file mode 100644 index 00000000000..305205cbf0d --- /dev/null +++ b/apps/server/src/modules/h5p-editor/libraryStorage/libraryStorage.ts @@ -0,0 +1,413 @@ +import { + InstalledLibrary, + LibraryName, + type IAdditionalLibraryMetadata, + type IFileStats, + type IInstalledLibrary, + type ILibraryMetadata, + type ILibraryName, + type ILibraryStorage, +} from '@lumieducation/h5p-server'; +import { Injectable } from '@nestjs/common'; + +import fsSync, { constants as FSConstants } from 'node:fs'; +import fs from 'node:fs/promises'; +import path from 'node:path'; +import type { Readable } from 'stream'; + +@Injectable() +export class LibraryStorage implements ILibraryStorage { + /** + * @param libraryDirectory Path of the directory in which the libraries are stored. Will be created if it does not exist. + */ + public constructor(private libraryDirectory: string) { + fsSync.mkdirSync(libraryDirectory, { recursive: true }); + } + + /** + * Returns the directory of the library. + * @param library + * @returns the absolute path to the library directory + */ + private getDirectoryPath(library: ILibraryName): string { + const uberName = LibraryName.toUberName(library); + const directoryPath = path.join(this.libraryDirectory, uberName); + return directoryPath; + } + + /** + * Returns the path of the file from the library. + * @param library + * @param filename + * @returns the absolute path to the file + */ + private getFilePath(library: ILibraryName, filename: string): string { + const uberName = LibraryName.toUberName(library); + const filePath = path.join(this.libraryDirectory, uberName, filename); + return filePath; + } + + /** + * Checks if the filename is absolute or traverses outside the directory. + * Throws an error if the filename is illegal. + * @param filename the requested file + */ + private checkFilename(filename: string): void { + if (path.normalize(filename).startsWith(`..${path.sep}`) || path.isAbsolute(filename)) { + throw new Error('Illegal filename'); + } + } + + /** + * Checks if the path can be accessed + * @param filePath + * @param options file access constant + */ + private async pathAccessible(filePath: string, options = FSConstants.F_OK) { + try { + await fs.access(filePath, options); + return true; + } catch (err) { + return false; + } + } + + /** + * Adds a file to a library. Library metadata must be installed using `installLibrary` first. + * @param library + * @param filename + * @param dataStream + * @returns true if successful + */ + public async addFile(library: ILibraryName, filename: string, dataStream: Readable): Promise { + this.checkFilename(filename); + + if (!(await this.isInstalled(library))) { + throw new Error(`Could not add file to library ${LibraryName.toUberName(library)}`); + } + + const fullPath = this.getFilePath(library, filename); + await fs.mkdir(path.dirname(fullPath), { recursive: true }); + await fs.writeFile(fullPath, dataStream); + + return true; + } + + /** + * Adds the metadata of the library + * @param libraryMetadata + * @param restricted + * @returns The newly created library object + */ + public async addLibrary(libraryMetadata: ILibraryMetadata, restricted: boolean): Promise { + const library = new InstalledLibrary( + libraryMetadata.machineName, + libraryMetadata.majorVersion, + libraryMetadata.minorVersion, + libraryMetadata.patchVersion, + restricted + ); + + const libraryPath = this.getDirectoryPath(library); + + if (await this.pathAccessible(libraryPath)) { + throw new Error(`Can't add library because it already exists`); + } + + try { + await fs.mkdir(libraryPath, { recursive: true }); + + const libraryMetadataPath = this.getFilePath(library, 'library.json'); + await fs.writeFile(libraryMetadataPath, JSON.stringify(libraryMetadata, undefined, 2)); + return library; + } catch (error) { + await fs.rm(libraryPath, { recursive: true, force: true }); + throw error; + } + } + + /** + * Removes all files of a library, but keeps the metadata + * @param library + */ + public async clearFiles(library: ILibraryName): Promise { + if (!(await this.isInstalled(library))) { + throw new Error("Can't clear library files, because it is not installed"); + } + + const fullLibraryPath = this.getDirectoryPath(library); + const files = (await fs.readdir(fullLibraryPath)).filter((file) => file !== 'library.json'); + + await Promise.all(files.map((entry) => fs.rm(this.getFilePath(library, entry), { recursive: true, force: true }))); + } + + /** + * Deletes metadata and all files of the library + * @param library + */ + public async deleteLibrary(library: ILibraryName): Promise { + const libPath = this.getDirectoryPath(library); + + if (!(await this.pathAccessible(libPath))) { + throw new Error("Can't delete library, because it is not installed"); + } + + await fs.rm(libPath, { recursive: true, force: true }); + } + + /** + * Checks if the file exists in the library + * @param library + * @param filename + * @returns true if the file exists, false otherwise + */ + public async fileExists(library: ILibraryName, filename: string): Promise { + this.checkFilename(filename); + + return this.pathAccessible(this.getFilePath(library, filename)); + } + + /** + * Counts how often libraries are listed in the dependencies of other libraries and returns a list of the number. + * @returns an object with ubernames as key. + */ + public async getAllDependentsCount(): Promise<{ [ubername: string]: number }> { + const installedLibraries = await this.getInstalledLibraryNames(); + const librariesMetadata = await Promise.all(installedLibraries.map((lib) => this.getLibrary(lib))); + + const librariesMetadataMap = new Map( + installedLibraries.map((library, idx) => [LibraryName.toUberName(library), librariesMetadata[idx]]) + ); + + // Remove circular dependencies + for (const libraryMetadata of librariesMetadata) { + for (const dependency of libraryMetadata.editorDependencies ?? []) { + const ubername = LibraryName.toUberName(dependency); + + const dependencyMetadata = librariesMetadataMap.get(ubername); + + if (dependencyMetadata?.preloadedDependencies) { + const index = dependencyMetadata.preloadedDependencies.findIndex((libName) => + LibraryName.equal(libName, libraryMetadata) + ); + + if (index >= 0) { + dependencyMetadata.preloadedDependencies.splice(index, 1); + } + } + } + } + + // Count dependencies + const dependencies: { [ubername: string]: number } = {}; + for (const libraryData of librariesMetadata) { + const { preloadedDependencies = [], editorDependencies = [], dynamicDependencies = [] } = libraryData; + + for (const dependency of preloadedDependencies.concat(editorDependencies, dynamicDependencies)) { + const ubername = LibraryName.toUberName(dependency); + dependencies[ubername] = (dependencies[ubername] ?? 0) + 1; + } + } + + return dependencies; + } + + /** + * Counts how many dependents the library has. + * @param library + * @returns the count + */ + public async getDependentsCount(library: ILibraryName): Promise { + const allDependencies = await this.getAllDependentsCount(); + return allDependencies[LibraryName.toUberName(library)] ?? 0; + } + + /** + * Returns the file as a JSON-parsed object + * @param library + * @param file + */ + public async getFileAsJson(library: ILibraryName, file: 'library.json'): Promise; + public async getFileAsJson(library: ILibraryName, file: string): Promise; + public async getFileAsJson(library: ILibraryName, file: string): Promise { + const content = await this.getFileAsString(library, file); + return JSON.parse(content) as unknown; + } + + /** + * Returns the file as a utf-8 string + * @param library + * @param file + */ + public async getFileAsString(library: ILibraryName, file: string): Promise { + const contents = await fs.readFile(this.getFilePath(library, file), 'utf-8'); + return contents; + } + + /** + * Returns information about a library file + * @param library + * @param file + */ + public async getFileStats(library: ILibraryName, file: string): Promise { + if (!(await this.fileExists(library, file))) { + throw new Error('The requested file does not exist'); + } + + const stats = fs.stat(this.getFilePath(library, file)); + return stats; + } + + /** + * Returns a readable stream of the file's contents. + * @param library + * @param file + */ + public getFileStream(library: ILibraryName, file: string): Promise { + const readStream = fsSync.createReadStream(this.getFilePath(library, file)); + return Promise.resolve(readStream); + } + + /** + * Lists all installed libraries or the installed libraries that have the machine name + * @param machineName (optional) only return libraries that have this machine name + */ + public async getInstalledLibraryNames(machineName?: string): Promise { + const nameRegex = /^([\w.]+)-(\d+)\.(\d+)$/i; // abc-12.34 + const libDirEntries = await fs.readdir(this.libraryDirectory); + + const libraries = libDirEntries + .filter((name) => nameRegex.test(name)) + .map((name) => LibraryName.fromUberName(name)) + .filter((lib) => !machineName || lib.machineName === machineName); + + return libraries; + } + + /** + * Lists all languages supported by a library + * @param library + */ + public async getLanguages(library: ILibraryName): Promise { + const languageDirEntries = await fs.readdir(this.getFilePath(library, 'language')); + + const languages = languageDirEntries + .filter((file) => path.extname(file) === '.json') + .map((file) => path.basename(file, '.json')); + + return languages; + } + + /** + * Returns the library metadata + * @param library + */ + public async getLibrary(library: ILibraryName): Promise { + if (!(await this.isInstalled(library))) { + throw new Error('The requested library does not exist'); + } + + const libraryMetadata = await this.getFileAsJson(library, 'library.json'); + const installedLibrary = InstalledLibrary.fromMetadata(libraryMetadata); + + return installedLibrary; + } + + /** + * Checks if a library is installed + * @param library + */ + public async isInstalled(library: ILibraryName): Promise { + return this.pathAccessible(this.getFilePath(library, 'library.json')); + } + + /** + * Lists all addons that are installed in the system. + */ + public async listAddons(): Promise { + const installedLibraryNames = await this.getInstalledLibraryNames(); + const installedLibraries = await Promise.all(installedLibraryNames.map((addonName) => this.getLibrary(addonName))); + const addons = installedLibraries.filter((library) => library.addTo !== undefined); + + return addons; + } + + /** + * Returns all files that are a part of the library + * @param library + * @returns an array of filenames + */ + public async listFiles(library: ILibraryName): Promise { + const libPath = this.getDirectoryPath(library); + + // Returns an async iterator + async function* getAllFiles(filepath: string): AsyncGenerator { + const entries = await fs.readdir(filepath, { withFileTypes: true }); + + for (const file of entries) { + if (file.isDirectory()) { + yield* getAllFiles(path.join(filepath, file.name)); + } else { + yield path.join(filepath, file.name); + } + } + } + + const files: string[] = []; + for await (const file of getAllFiles(libPath)) { + files.push(file); + } + + return files; + } + + /** + * Updates the additional metadata properties that are added to the stored libraries. + * @param library + * @param additionalMetadata + */ + public async updateAdditionalMetadata( + library: ILibraryName, + additionalMetadata: Partial + ): Promise { + const libraryMetadata = await this.getLibrary(library); + + let dirty = false; + for (const [property, value] of Object.entries(additionalMetadata)) { + if (value !== libraryMetadata[property]) { + libraryMetadata[property] = value; + dirty = true; + } + } + + // Don't write file if nothing has changed + if (!dirty) { + return false; + } + + try { + await fs.writeFile(this.getFilePath(library, 'library.json'), JSON.stringify(libraryMetadata, undefined, 2)); + return true; + } catch (error) { + throw new Error('Could not update metadata'); + } + } + + /** + * Updates the library metadata + * @param libraryMetadata + */ + async updateLibrary(libraryMetadata: ILibraryMetadata): Promise { + const libPath = this.getDirectoryPath(libraryMetadata); + + if (!(await this.pathAccessible(libPath))) { + throw new Error('Library is not installed'); + } + + const libraryJsonPath = this.getFilePath(libraryMetadata, 'library.json'); + await fs.writeFile(libraryJsonPath, JSON.stringify(libraryMetadata, undefined, 2)); + + const newLibrary = InstalledLibrary.fromMetadata(libraryMetadata); + return newLibrary; + } +} From bc2e26f2f36512a63f533973d9c5c36a0bdbdc55 Mon Sep 17 00:00:00 2001 From: Majed Mak <132336669+MajedAlaitwniCap@users.noreply.github.com> Date: Wed, 7 Jun 2023 13:52:57 +0200 Subject: [PATCH 004/134] h5p editor: added deployment which uses existing template (#4136) Co-authored-by: Andre Blome Co-authored-by: Stephan Krause <101647440+SteKrause@users.noreply.github.com> --- ansible/roles/schulcloud-server-core/tasks/main.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/ansible/roles/schulcloud-server-core/tasks/main.yml b/ansible/roles/schulcloud-server-core/tasks/main.yml index f444d31a57c..9eca99b1533 100644 --- a/ansible/roles/schulcloud-server-core/tasks/main.yml +++ b/ansible/roles/schulcloud-server-core/tasks/main.yml @@ -72,6 +72,13 @@ namespace: "{{ NAMESPACE }}" template: api-fwu-deployment.yml.j2 when: FEATURE_FWU_CONTENT_ENABLED is defined and FEATURE_FWU_CONTENT_ENABLED|bool + + - name: H5pEditorDeployment + kubernetes.core.k8s: + kubeconfig: ~/.kube/config + namespace: "{{ NAMESPACE }}" + template: api-h5p-deployment.yml.j2 + when: FEATURE_H5P_EDITOR_ENABLED is defined and FEATURE_H5P_EDITOR_ENABLED|bool - name: Delete Files CronJob kubernetes.core.k8s: From 1ef58915050567492741732b96eb8b6784abdad8 Mon Sep 17 00:00:00 2001 From: Stephan Krause <101647440+SteKrause@users.noreply.github.com> Date: Wed, 7 Jun 2023 14:09:35 +0200 Subject: [PATCH 005/134] Thr 5 h5p implementation endpoints (#4169) * Created H5P microservice * Add kubernetes files for h5p microservice * Added @lumieducation/h5p-server package * Don't use mock auth for testing * add ContentStorage with interface IContentStorage * Fix api tests to use new TestApiClient * WIP: H5P editor: temp file storage * WIP: H5P editor: added data classes * add addContent() * implement addFile(), contentExists(), deleteContent() * implement deleteFile(), fileExists() * add getFileStats(), getFileStream() * add getMetadata(), getParameters(), getUsage() * add getUserPermissions(), listContent() * add listFiles(), sanitizeFilename() * refactor sanitizeFileneame * Implemented library storage * add user check for getMetadata and getParameters * fix existsOrCreateDir * h5p editor: added deployment which uses existing template * fix deleteContent and fileExists * Tests for librray storage * resolve merge conflict leftovers * fix fileExists and contentExists, refactor methods * add unit tests for contentStorage * delete comments in addFile * fix addFile test and change descriptions * fix getUsage * fix getUsage test * delete TODO * full test coverage * Moved files * Implemented library storage * Tests for librray storage * full test coverage * Moved files * add error message to contentExists + tests * add test for empty contentId at fileEsists * remove unused private sanitize method * adjust errorhandling + add tests for error cases * add tests and fix error cases * replace math.random * change regex in checkfilename * delete unused code * change regex in checkfilename * refactor tests and content storage implementation * change any values to unknown * fix create content id * Fix issues from merging main into THR-2 * refactor and fix exist boolean in createContentId * fix test can not createContentId * Stubbed endpoints * Editor and Player service * Added H5P Usecase * h5p editor: temp file storage implementation completed * h5p editor: temp file storage tests added * h5p editor: temp file storage moved * h5p editor: temp storage files moved * File streaming * Post Ajax endpoint * Merge branch 'THR-8-h5p-api-endpoints' of github.com:hpi-schul-cloud/schulcloud-server into THR-5-h5p-implementation-endpoints * Remove @nestjs/serve-static dependency * Editor working more reliably * Disable saving of userstate * Organized code * More organization * Tests for getAjax usecase * add tests for h5p controller * Tests and organization * add import of FilesStorageAMQPModule to h5p-editor module * Switched over to storage implementations * Organized modules * change stringPath of createNewEditor * Testing for files in UC * Testing content parameters in UC * change AjaxPostBodyParams to undefined if empty * change save api endpoint * Fixed file streaming * Fixed h5p uploading * Update temporary-file-storage.ts Create temporary file folder * merge save and create endpoints to one get and post endpoint * create folder if content will be created * adjust paths at api tests * rename usecase to getH5pEditor * Use real user * Allow files in subdirectories * Testing for h5p files * API tests for internal AJAX endpoint * Test range requests for storages * add unit-tests to usecases * add api tests for h5p endpoints * add api test save or create * adjust create or save api test --------- Co-authored-by: Marvin Rode Co-authored-by: Marvin Rode (Cap) <127723478+marode-cap@users.noreply.github.com> Co-authored-by: Andre Blome --- apps/server/src/apps/h5p-editor.app.ts | 10 + .../api-test/h5p-editor-ajax.api.spec.ts | 172 + .../api-test/h5p-editor-delete.api.spec.ts | 100 + .../api-test/h5p-editor-files.api.spec.ts | 298 ++ .../h5p-editor-get-editor.api.spec.ts | 98 + .../h5p-editor-get-player.api.spec.ts | 97 + .../h5p-editor-save-create.api.spec.ts | 143 + .../api-test/h5p-editor.api.spec.ts | 106 - .../controller/dto/ajax/get.params.ts | 23 + .../h5p-editor/controller/dto/ajax/index.ts | 3 + .../controller/dto/ajax/post.body.params.ts | 72 + .../controller/dto/ajax/post.params.ts | 27 + .../controller/dto/content-file.url.params.ts | 14 + .../controller/dto/h5p-editor.params.ts | 59 + .../h5p-editor/controller/dto/index.ts | 4 + .../controller/dto/library-file.url.params.ts | 14 + .../controller/h5p-editor.controller.ts | 182 +- .../h5p-editor/h5p-editor-test.module.ts | 23 +- .../modules/h5p-editor/h5p-editor.module.ts | 24 +- .../service/h5p-ajax-endpoint.service.ts | 11 + .../h5p-editor/service/h5p-editor.service.ts | 33 + .../h5p-editor/service/h5p-player.service.ts | 30 + .../src/modules/h5p-editor/service/index.ts | 3 + .../modules/h5p-editor/uc/h5p-ajax.uc.spec.ts | 204 ++ .../h5p-editor/uc/h5p-delete.uc.spec.ts | 74 + .../h5p-editor/uc/h5p-files.uc.spec.ts | 331 ++ .../h5p-editor/uc/h5p-get-editor.uc.spec.ts | 79 + .../h5p-editor/uc/h5p-get-player.uc.spec.ts | 68 + .../h5p-editor/uc/h5p-save-create.uc.spec.ts | 109 + .../src/modules/h5p-editor/uc/h5p.uc.ts | 269 ++ .../server/static-assets/h5p/core/LICENSE.txt | 674 ++++ apps/server/static-assets/h5p/core/README.txt | 14 + .../static-assets/h5p/core/doc/spec_en.html | 168 + .../h5p/core/fonts/h5p-core-23.eot | Bin 0 -> 9188 bytes .../h5p/core/fonts/h5p-core-23.svg | 62 + .../h5p/core/fonts/h5p-core-23.ttf | Bin 0 -> 9020 bytes .../h5p/core/fonts/h5p-core-23.woff | Bin 0 -> 9096 bytes .../static-assets/h5p/core/images/h5p.svg | 16 + .../h5p/core/images/throbber.gif | Bin 0 -> 1638 bytes .../h5p/core/js/h5p-action-bar.js | 100 + .../h5p/core/js/h5p-confirmation-dialog.js | 410 +++ .../h5p/core/js/h5p-content-type.js | 41 + .../core/js/h5p-content-upgrade-process.js | 313 ++ .../h5p/core/js/h5p-content-upgrade-worker.js | 63 + .../h5p/core/js/h5p-content-upgrade.js | 445 +++ .../h5p/core/js/h5p-data-view.js | 442 +++ .../h5p/core/js/h5p-display-options.js | 54 + .../static-assets/h5p/core/js/h5p-embed.js | 75 + .../h5p/core/js/h5p-event-dispatcher.js | 258 ++ .../h5p/core/js/h5p-library-details.js | 297 ++ .../h5p/core/js/h5p-library-list.js | 140 + .../static-assets/h5p/core/js/h5p-resizer.js | 131 + .../static-assets/h5p/core/js/h5p-utils.js | 506 +++ .../static-assets/h5p/core/js/h5p-version.js | 40 + .../h5p/core/js/h5p-x-api-event.js | 331 ++ .../static-assets/h5p/core/js/h5p-x-api.js | 119 + apps/server/static-assets/h5p/core/js/h5p.js | 2857 +++++++++++++++++ .../static-assets/h5p/core/js/jquery.js | 20 + .../h5p/core/js/request-queue.js | 436 +++ .../h5p/core/js/settings/h5p-disable-hub.js | 68 + .../h5p/core/styles/h5p-admin.css | 358 +++ .../core/styles/h5p-confirmation-dialog.css | 183 ++ .../h5p/core/styles/h5p-core-button.css | 60 + .../static-assets/h5p/core/styles/h5p.css | 565 ++++ apps/server/static-assets/h5p/core/v1.24.0 | 0 .../server/static-assets/h5p/editor/README.md | 8 + .../h5p/editor/ckeditor/CHANGES.md | 1703 ++++++++++ .../h5p/editor/ckeditor/LICENSE.md | 1420 ++++++++ .../h5p/editor/ckeditor/adapters/jquery.js | 10 + .../h5p/editor/ckeditor/build-config.js | 162 + .../h5p/editor/ckeditor/ckeditor.js | 1060 ++++++ .../h5p/editor/ckeditor/config.js | 45 + .../h5p/editor/ckeditor/contents.css | 208 ++ .../h5p/editor/ckeditor/lang/af.js | 5 + .../h5p/editor/ckeditor/lang/ar.js | 5 + .../h5p/editor/ckeditor/lang/az.js | 5 + .../h5p/editor/ckeditor/lang/bg.js | 5 + .../h5p/editor/ckeditor/lang/bn.js | 5 + .../h5p/editor/ckeditor/lang/bs.js | 5 + .../h5p/editor/ckeditor/lang/ca.js | 5 + .../h5p/editor/ckeditor/lang/cs.js | 5 + .../h5p/editor/ckeditor/lang/cy.js | 5 + .../h5p/editor/ckeditor/lang/da.js | 5 + .../h5p/editor/ckeditor/lang/de-ch.js | 5 + .../h5p/editor/ckeditor/lang/de.js | 5 + .../h5p/editor/ckeditor/lang/el.js | 5 + .../h5p/editor/ckeditor/lang/en-au.js | 5 + .../h5p/editor/ckeditor/lang/en-ca.js | 5 + .../h5p/editor/ckeditor/lang/en-gb.js | 5 + .../h5p/editor/ckeditor/lang/en.js | 5 + .../h5p/editor/ckeditor/lang/eo.js | 5 + .../h5p/editor/ckeditor/lang/es-mx.js | 5 + .../h5p/editor/ckeditor/lang/es.js | 5 + .../h5p/editor/ckeditor/lang/et.js | 5 + .../h5p/editor/ckeditor/lang/eu.js | 5 + .../h5p/editor/ckeditor/lang/fa.js | 5 + .../h5p/editor/ckeditor/lang/fi.js | 5 + .../h5p/editor/ckeditor/lang/fo.js | 5 + .../h5p/editor/ckeditor/lang/fr-ca.js | 5 + .../h5p/editor/ckeditor/lang/fr.js | 5 + .../h5p/editor/ckeditor/lang/gl.js | 5 + .../h5p/editor/ckeditor/lang/gu.js | 5 + .../h5p/editor/ckeditor/lang/he.js | 5 + .../h5p/editor/ckeditor/lang/hi.js | 5 + .../h5p/editor/ckeditor/lang/hr.js | 5 + .../h5p/editor/ckeditor/lang/hu.js | 5 + .../h5p/editor/ckeditor/lang/id.js | 5 + .../h5p/editor/ckeditor/lang/is.js | 5 + .../h5p/editor/ckeditor/lang/it.js | 5 + .../h5p/editor/ckeditor/lang/ja.js | 5 + .../h5p/editor/ckeditor/lang/ka.js | 5 + .../h5p/editor/ckeditor/lang/km.js | 5 + .../h5p/editor/ckeditor/lang/ko.js | 5 + .../h5p/editor/ckeditor/lang/ku.js | 5 + .../h5p/editor/ckeditor/lang/lt.js | 5 + .../h5p/editor/ckeditor/lang/lv.js | 5 + .../h5p/editor/ckeditor/lang/mk.js | 5 + .../h5p/editor/ckeditor/lang/mn.js | 5 + .../h5p/editor/ckeditor/lang/ms.js | 5 + .../h5p/editor/ckeditor/lang/nb.js | 5 + .../h5p/editor/ckeditor/lang/nl.js | 5 + .../h5p/editor/ckeditor/lang/no.js | 5 + .../h5p/editor/ckeditor/lang/oc.js | 5 + .../h5p/editor/ckeditor/lang/pl.js | 5 + .../h5p/editor/ckeditor/lang/pt-br.js | 5 + .../h5p/editor/ckeditor/lang/pt.js | 5 + .../h5p/editor/ckeditor/lang/ro.js | 5 + .../h5p/editor/ckeditor/lang/ru.js | 5 + .../h5p/editor/ckeditor/lang/si.js | 5 + .../h5p/editor/ckeditor/lang/sk.js | 5 + .../h5p/editor/ckeditor/lang/sl.js | 5 + .../h5p/editor/ckeditor/lang/sq.js | 5 + .../h5p/editor/ckeditor/lang/sr-latn.js | 5 + .../h5p/editor/ckeditor/lang/sr.js | 5 + .../h5p/editor/ckeditor/lang/sv.js | 5 + .../h5p/editor/ckeditor/lang/th.js | 5 + .../h5p/editor/ckeditor/lang/tr.js | 5 + .../h5p/editor/ckeditor/lang/tt.js | 5 + .../h5p/editor/ckeditor/lang/ug.js | 5 + .../h5p/editor/ckeditor/lang/uk.js | 5 + .../h5p/editor/ckeditor/lang/vi.js | 5 + .../h5p/editor/ckeditor/lang/zh-cn.js | 5 + .../h5p/editor/ckeditor/lang/zh.js | 5 + .../plugins/a11yhelp/dialogs/a11yhelp.js | 10 + .../dialogs/lang/_translationstatus.txt | 25 + .../plugins/a11yhelp/dialogs/lang/af.js | 11 + .../plugins/a11yhelp/dialogs/lang/ar.js | 11 + .../plugins/a11yhelp/dialogs/lang/az.js | 11 + .../plugins/a11yhelp/dialogs/lang/bg.js | 11 + .../plugins/a11yhelp/dialogs/lang/ca.js | 13 + .../plugins/a11yhelp/dialogs/lang/cs.js | 12 + .../plugins/a11yhelp/dialogs/lang/cy.js | 11 + .../plugins/a11yhelp/dialogs/lang/da.js | 11 + .../plugins/a11yhelp/dialogs/lang/de-ch.js | 12 + .../plugins/a11yhelp/dialogs/lang/de.js | 13 + .../plugins/a11yhelp/dialogs/lang/el.js | 13 + .../plugins/a11yhelp/dialogs/lang/en-au.js | 11 + .../plugins/a11yhelp/dialogs/lang/en-gb.js | 11 + .../plugins/a11yhelp/dialogs/lang/en.js | 11 + .../plugins/a11yhelp/dialogs/lang/eo.js | 13 + .../plugins/a11yhelp/dialogs/lang/es-mx.js | 13 + .../plugins/a11yhelp/dialogs/lang/es.js | 13 + .../plugins/a11yhelp/dialogs/lang/et.js | 11 + .../plugins/a11yhelp/dialogs/lang/eu.js | 12 + .../plugins/a11yhelp/dialogs/lang/fa.js | 11 + .../plugins/a11yhelp/dialogs/lang/fi.js | 11 + .../plugins/a11yhelp/dialogs/lang/fo.js | 11 + .../plugins/a11yhelp/dialogs/lang/fr-ca.js | 11 + .../plugins/a11yhelp/dialogs/lang/fr.js | 13 + .../plugins/a11yhelp/dialogs/lang/gl.js | 12 + .../plugins/a11yhelp/dialogs/lang/gu.js | 11 + .../plugins/a11yhelp/dialogs/lang/he.js | 11 + .../plugins/a11yhelp/dialogs/lang/hi.js | 11 + .../plugins/a11yhelp/dialogs/lang/hr.js | 11 + .../plugins/a11yhelp/dialogs/lang/hu.js | 12 + .../plugins/a11yhelp/dialogs/lang/id.js | 11 + .../plugins/a11yhelp/dialogs/lang/it.js | 13 + .../plugins/a11yhelp/dialogs/lang/ja.js | 9 + .../plugins/a11yhelp/dialogs/lang/km.js | 11 + .../plugins/a11yhelp/dialogs/lang/ko.js | 10 + .../plugins/a11yhelp/dialogs/lang/ku.js | 11 + .../plugins/a11yhelp/dialogs/lang/lt.js | 11 + .../plugins/a11yhelp/dialogs/lang/lv.js | 12 + .../plugins/a11yhelp/dialogs/lang/mk.js | 11 + .../plugins/a11yhelp/dialogs/lang/mn.js | 11 + .../plugins/a11yhelp/dialogs/lang/nb.js | 12 + .../plugins/a11yhelp/dialogs/lang/nl.js | 12 + .../plugins/a11yhelp/dialogs/lang/no.js | 11 + .../plugins/a11yhelp/dialogs/lang/oc.js | 12 + .../plugins/a11yhelp/dialogs/lang/pl.js | 13 + .../plugins/a11yhelp/dialogs/lang/pt-br.js | 13 + .../plugins/a11yhelp/dialogs/lang/pt.js | 12 + .../plugins/a11yhelp/dialogs/lang/ro.js | 12 + .../plugins/a11yhelp/dialogs/lang/ru.js | 11 + .../plugins/a11yhelp/dialogs/lang/si.js | 10 + .../plugins/a11yhelp/dialogs/lang/sk.js | 11 + .../plugins/a11yhelp/dialogs/lang/sl.js | 11 + .../plugins/a11yhelp/dialogs/lang/sq.js | 12 + .../plugins/a11yhelp/dialogs/lang/sr-latn.js | 12 + .../plugins/a11yhelp/dialogs/lang/sr.js | 12 + .../plugins/a11yhelp/dialogs/lang/sv.js | 11 + .../plugins/a11yhelp/dialogs/lang/th.js | 11 + .../plugins/a11yhelp/dialogs/lang/tr.js | 12 + .../plugins/a11yhelp/dialogs/lang/tt.js | 11 + .../plugins/a11yhelp/dialogs/lang/ug.js | 12 + .../plugins/a11yhelp/dialogs/lang/uk.js | 12 + .../plugins/a11yhelp/dialogs/lang/vi.js | 11 + .../plugins/a11yhelp/dialogs/lang/zh-cn.js | 9 + .../plugins/a11yhelp/dialogs/lang/zh.js | 9 + .../plugins/clipboard/dialogs/paste.js | 11 + .../colordialog/dialogs/colordialog.css | 20 + .../colordialog/dialogs/colordialog.js | 14 + .../plugins/dialog/dialogDefinition.js | 4 + .../h5p/editor/ckeditor/plugins/icons.png | Bin 0 -> 5190 bytes .../editor/ckeditor/plugins/icons_hidpi.png | Bin 0 -> 16340 bytes .../ckeditor/plugins/lineheight/LICENSE | 22 + .../ckeditor/plugins/lineheight/README.md | 2 + .../ckeditor/plugins/lineheight/readme.txt | 30 + .../ckeditor/plugins/link/dialogs/anchor.js | 8 + .../ckeditor/plugins/link/dialogs/link.js | 30 + .../ckeditor/plugins/link/images/anchor.png | Bin 0 -> 752 bytes .../plugins/link/images/hidpi/anchor.png | Bin 0 -> 1109 bytes .../magicline/images/hidpi/icon-rtl.png | Bin 0 -> 176 bytes .../plugins/magicline/images/hidpi/icon.png | Bin 0 -> 199 bytes .../plugins/magicline/images/icon-rtl.png | Bin 0 -> 138 bytes .../plugins/magicline/images/icon.png | Bin 0 -> 133 bytes .../plugins/pastefromword/filter/default.js | 55 + .../plugins/removeRedundantNBSP/plugin.js | 29 + .../dialogs/lang/_translationstatus.txt | 20 + .../plugins/specialchar/dialogs/lang/af.js | 13 + .../plugins/specialchar/dialogs/lang/ar.js | 13 + .../plugins/specialchar/dialogs/lang/az.js | 10 + .../plugins/specialchar/dialogs/lang/bg.js | 13 + .../plugins/specialchar/dialogs/lang/ca.js | 14 + .../plugins/specialchar/dialogs/lang/cs.js | 13 + .../plugins/specialchar/dialogs/lang/cy.js | 14 + .../plugins/specialchar/dialogs/lang/da.js | 11 + .../plugins/specialchar/dialogs/lang/de-ch.js | 13 + .../plugins/specialchar/dialogs/lang/de.js | 13 + .../plugins/specialchar/dialogs/lang/el.js | 13 + .../plugins/specialchar/dialogs/lang/en-au.js | 13 + .../plugins/specialchar/dialogs/lang/en-ca.js | 13 + .../plugins/specialchar/dialogs/lang/en-gb.js | 13 + .../plugins/specialchar/dialogs/lang/en.js | 13 + .../plugins/specialchar/dialogs/lang/eo.js | 12 + .../plugins/specialchar/dialogs/lang/es-mx.js | 13 + .../plugins/specialchar/dialogs/lang/es.js | 13 + .../plugins/specialchar/dialogs/lang/et.js | 13 + .../plugins/specialchar/dialogs/lang/eu.js | 13 + .../plugins/specialchar/dialogs/lang/fa.js | 12 + .../plugins/specialchar/dialogs/lang/fi.js | 13 + .../plugins/specialchar/dialogs/lang/fr-ca.js | 10 + .../plugins/specialchar/dialogs/lang/fr.js | 12 + .../plugins/specialchar/dialogs/lang/gl.js | 13 + .../plugins/specialchar/dialogs/lang/he.js | 12 + .../plugins/specialchar/dialogs/lang/hr.js | 13 + .../plugins/specialchar/dialogs/lang/hu.js | 12 + .../plugins/specialchar/dialogs/lang/id.js | 13 + .../plugins/specialchar/dialogs/lang/it.js | 14 + .../plugins/specialchar/dialogs/lang/ja.js | 9 + .../plugins/specialchar/dialogs/lang/km.js | 13 + .../plugins/specialchar/dialogs/lang/ko.js | 10 + .../plugins/specialchar/dialogs/lang/ku.js | 13 + .../plugins/specialchar/dialogs/lang/lt.js | 13 + .../plugins/specialchar/dialogs/lang/lv.js | 13 + .../plugins/specialchar/dialogs/lang/nb.js | 11 + .../plugins/specialchar/dialogs/lang/nl.js | 13 + .../plugins/specialchar/dialogs/lang/no.js | 11 + .../plugins/specialchar/dialogs/lang/oc.js | 12 + .../plugins/specialchar/dialogs/lang/pl.js | 12 + .../plugins/specialchar/dialogs/lang/pt-br.js | 11 + .../plugins/specialchar/dialogs/lang/pt.js | 13 + .../plugins/specialchar/dialogs/lang/ro.js | 13 + .../plugins/specialchar/dialogs/lang/ru.js | 13 + .../plugins/specialchar/dialogs/lang/si.js | 13 + .../plugins/specialchar/dialogs/lang/sk.js | 13 + .../plugins/specialchar/dialogs/lang/sl.js | 12 + .../plugins/specialchar/dialogs/lang/sq.js | 13 + .../specialchar/dialogs/lang/sr-latn.js | 13 + .../plugins/specialchar/dialogs/lang/sr.js | 13 + .../plugins/specialchar/dialogs/lang/sv.js | 11 + .../plugins/specialchar/dialogs/lang/th.js | 13 + .../plugins/specialchar/dialogs/lang/tr.js | 12 + .../plugins/specialchar/dialogs/lang/tt.js | 13 + .../plugins/specialchar/dialogs/lang/ug.js | 13 + .../plugins/specialchar/dialogs/lang/uk.js | 12 + .../plugins/specialchar/dialogs/lang/vi.js | 14 + .../plugins/specialchar/dialogs/lang/zh-cn.js | 9 + .../plugins/specialchar/dialogs/lang/zh.js | 9 + .../specialchar/dialogs/specialchar.js | 14 + .../ckeditor/plugins/table/dialogs/table.js | 21 + .../plugins/tabletools/dialogs/tableCell.js | 19 + .../editor/ckeditor/samples/css/samples.css | 1637 ++++++++++ .../ckeditor/samples/img/github-top.png | Bin 0 -> 383 bytes .../editor/ckeditor/samples/img/header-bg.png | Bin 0 -> 13086 bytes .../ckeditor/samples/img/header-separator.png | Bin 0 -> 123 bytes .../h5p/editor/ckeditor/samples/img/logo.png | Bin 0 -> 5634 bytes .../h5p/editor/ckeditor/samples/img/logo.svg | 13 + .../ckeditor/samples/img/navigation-tip.png | Bin 0 -> 12029 bytes .../h5p/editor/ckeditor/samples/index.html | 128 + .../h5p/editor/ckeditor/samples/js/sample.js | 53 + .../h5p/editor/ckeditor/samples/js/sf.js | 17 + .../h5p/editor/ckeditor/samples/old/ajax.html | 85 + .../h5p/editor/ckeditor/samples/old/api.html | 210 ++ .../editor/ckeditor/samples/old/appendto.html | 59 + .../samples/old/assets/inlineall/logo.png | Bin 0 -> 4283 bytes .../old/assets/outputxhtml/outputxhtml.css | 204 ++ .../samples/old/assets/posteddata.php | 59 + .../ckeditor/samples/old/assets/sample.jpg | Bin 0 -> 14449 bytes .../old/assets/uilanguages/languages.js | 7 + .../samples/old/autogrow/autogrow.html | 102 + .../ckeditor/samples/old/datafiltering.html | 508 +++ .../samples/old/dialog/assets/my_dialog.js | 48 + .../ckeditor/samples/old/dialog/dialog.html | 190 ++ .../ckeditor/samples/old/divreplace.html | 144 + .../samples/old/enterkey/enterkey.html | 106 + .../assets/outputforflash/outputforflash.fla | Bin 0 -> 85504 bytes .../assets/outputforflash/outputforflash.swf | Bin 0 -> 15571 bytes .../assets/outputforflash/swfobject.js | 19 + .../old/htmlwriter/outputforflash.html | 283 ++ .../samples/old/htmlwriter/outputhtml.html | 224 ++ .../editor/ckeditor/samples/old/index.html | 134 + .../ckeditor/samples/old/inlineall.html | 314 ++ .../ckeditor/samples/old/inlinebycode.html | 124 + .../ckeditor/samples/old/inlinetextarea.html | 113 + .../editor/ckeditor/samples/old/jquery.html | 103 + .../samples/old/magicline/magicline.html | 209 ++ .../editor/ckeditor/samples/old/readonly.html | 76 + .../ckeditor/samples/old/replacebyclass.html | 60 + .../ckeditor/samples/old/replacebycode.html | 59 + .../editor/ckeditor/samples/old/sample.css | 357 ++ .../h5p/editor/ckeditor/samples/old/sample.js | 50 + .../samples/old/sample_posteddata.php | 16 + .../editor/ckeditor/samples/old/tabindex.html | 78 + .../ckeditor/samples/old/toolbar/toolbar.html | 235 ++ .../editor/ckeditor/samples/old/uicolor.html | 72 + .../ckeditor/samples/old/uilanguages.html | 122 + .../samples/old/wysiwygarea/fullpage.html | 80 + .../ckeditor/samples/old/xhtmlstyle.html | 234 ++ .../toolbarconfigurator/css/fontello.css | 55 + .../toolbarconfigurator/font/LICENSE.txt | 10 + .../toolbarconfigurator/font/config.json | 28 + .../toolbarconfigurator/font/fontello.eot | Bin 0 -> 4988 bytes .../toolbarconfigurator/font/fontello.svg | 14 + .../toolbarconfigurator/font/fontello.ttf | Bin 0 -> 4820 bytes .../toolbarconfigurator/font/fontello.woff | Bin 0 -> 2904 bytes .../samples/toolbarconfigurator/index.html | 446 +++ .../js/abstracttoolbarmodifier.js | 13 + .../js/fulltoolbareditor.js | 9 + .../toolbarconfigurator/js/toolbarmodifier.js | 33 + .../js/toolbartextmodifier.js | 14 + .../skins/bootstrapck/.temp/css/dialog.css | 1 + .../skins/bootstrapck/.temp/css/dialog_ie.css | 1 + .../bootstrapck/.temp/css/dialog_ie7.css | 1 + .../bootstrapck/.temp/css/dialog_ie8.css | 1 + .../bootstrapck/.temp/css/dialog_iequirks.css | 1 + .../bootstrapck/.temp/css/dialog_opera.css | 1 + .../skins/bootstrapck/.temp/css/editor.css | 1 + .../bootstrapck/.temp/css/editor_gecko.css | 1 + .../skins/bootstrapck/.temp/css/editor_ie.css | 1 + .../bootstrapck/.temp/css/editor_ie7.css | 1 + .../bootstrapck/.temp/css/editor_ie8.css | 1 + .../bootstrapck/.temp/css/editor_iequirks.css | 1 + .../ckeditor/skins/bootstrapck/dialog.css | 1 + .../ckeditor/skins/bootstrapck/dialog_ie.css | 1 + .../ckeditor/skins/bootstrapck/dialog_ie7.css | 1 + .../ckeditor/skins/bootstrapck/dialog_ie8.css | 1 + .../skins/bootstrapck/dialog_iequirks.css | 1 + .../skins/bootstrapck/dialog_opera.css | 1 + .../ckeditor/skins/bootstrapck/editor.css | 1 + .../skins/bootstrapck/editor_gecko.css | 1 + .../ckeditor/skins/bootstrapck/editor_ie.css | 1 + .../ckeditor/skins/bootstrapck/editor_ie7.css | 1 + .../ckeditor/skins/bootstrapck/editor_ie8.css | 1 + .../skins/bootstrapck/editor_iequirks.css | 1 + .../ckeditor/skins/bootstrapck/icons.png | Bin 0 -> 5190 bytes .../skins/bootstrapck/icons_hidpi.png | Bin 0 -> 16340 bytes .../skins/bootstrapck/images/arrow.png | Bin 0 -> 261 bytes .../skins/bootstrapck/images/close.png | Bin 0 -> 415 bytes .../skins/bootstrapck/images/hidpi/close.png | Bin 0 -> 498 bytes .../bootstrapck/images/hidpi/lock-open.png | Bin 0 -> 573 bytes .../skins/bootstrapck/images/hidpi/lock.png | Bin 0 -> 571 bytes .../bootstrapck/images/hidpi/refresh.png | Bin 0 -> 867 bytes .../skins/bootstrapck/images/lock-open.png | Bin 0 -> 402 bytes .../skins/bootstrapck/images/lock.png | Bin 0 -> 413 bytes .../skins/bootstrapck/images/refresh.png | Bin 0 -> 532 bytes .../ckeditor/skins/bootstrapck/readme.md | 35 + .../sample/bootstrapck-sample.html | 127 + .../sample/css/bootstrapck-sample.css | 1 + .../skins/bootstrapck/sample/js/analytics.js | 4 + .../sample/js/jquery-1.11.0.min.js | 189 ++ .../browser-specific/gecko/editor_gecko.scss | 25 + .../scss/browser-specific/ie/dialog_ie.scss | 62 + .../scss/browser-specific/ie/editor_ie.scss | 71 + .../scss/browser-specific/ie7/dialog_ie7.scss | 68 + .../scss/browser-specific/ie7/editor_ie7.scss | 213 ++ .../scss/browser-specific/ie8/dialog_ie8.scss | 24 + .../scss/browser-specific/ie8/editor_ie8.scss | 27 + .../iequirks/dialog_iequirks.scss | 21 + .../iequirks/editor_iequirks.scss | 79 + .../browser-specific/opera/dialog_opera.scss | 31 + .../scss/components/_colorpanel.scss | 119 + .../scss/components/_elementspath.scss | 66 + .../bootstrapck/scss/components/_mainui.scss | 189 ++ .../bootstrapck/scss/components/_menu.scss | 182 ++ .../bootstrapck/scss/components/_panel.scss | 199 ++ .../bootstrapck/scss/components/_presets.scss | 32 + .../bootstrapck/scss/components/_reset.scss | 107 + .../scss/components/_richcombo.scss | 174 + .../bootstrapck/scss/components/_toolbar.scss | 317 ++ .../bootstrapck/scss/components/editor.scss | 66 + .../bootstrapck/scss/config/_colors.scss | 61 + .../bootstrapck/scss/config/_config.scss | 9 + .../bootstrapck/scss/config/_defaults.scss | 37 + .../skins/bootstrapck/scss/dialog/dialog.scss | 822 +++++ .../h5p/editor/ckeditor/styles.js | 137 + .../static-assets/h5p/editor/composer.json | 34 + .../static-assets/h5p/editor/images/add.png | Bin 0 -> 2410 bytes .../h5p/editor/images/binary-file.png | Bin 0 -> 6009 bytes .../h5p/editor/images/collapse.png | Bin 0 -> 203 bytes .../static-assets/h5p/editor/images/down.png | Bin 0 -> 223 bytes .../h5p/editor/images/expand.png | Bin 0 -> 201 bytes .../static-assets/h5p/editor/images/order.png | Bin 0 -> 464 bytes .../h5p/editor/images/remove.png | Bin 0 -> 603 bytes .../editor/images/transparent-background.png | Bin 0 -> 954 bytes .../h5p/editor/images/webm-file.png | Bin 0 -> 6760 bytes .../static-assets/h5p/editor/language/ar.js | 216 ++ .../static-assets/h5p/editor/language/bs.js | 216 ++ .../static-assets/h5p/editor/language/de.js | 216 ++ .../static-assets/h5p/editor/language/el.js | 216 ++ .../static-assets/h5p/editor/language/en.js | 218 ++ .../h5p/editor/language/es-cr.js | 216 ++ .../h5p/editor/language/es-mx.js | 216 ++ .../static-assets/h5p/editor/language/es.js | 218 ++ .../static-assets/h5p/editor/language/et.js | 218 ++ .../static-assets/h5p/editor/language/eu.js | 218 ++ .../static-assets/h5p/editor/language/fi.js | 216 ++ .../static-assets/h5p/editor/language/fr.js | 216 ++ .../static-assets/h5p/editor/language/it.js | 216 ++ .../static-assets/h5p/editor/language/nb.js | 216 ++ .../static-assets/h5p/editor/language/nl.js | 216 ++ .../static-assets/h5p/editor/language/nn.js | 216 ++ .../static-assets/h5p/editor/language/pl.js | 216 ++ .../h5p/editor/language/pt-br.js | 216 ++ .../static-assets/h5p/editor/language/pt.js | 216 ++ .../static-assets/h5p/editor/language/ru.js | 218 ++ .../static-assets/h5p/editor/language/tr.js | 216 ++ .../h5p/editor/libs/darkroom.css | 1 + .../static-assets/h5p/editor/libs/darkroom.js | 1 + .../static-assets/h5p/editor/libs/fabric.js | 8 + .../h5p/editor/libs/zebra_datepicker.min.js | 5 + .../h5p/editor/scripts/h5p-hub-client.js | 45 + .../h5p/editor/scripts/h5peditor-av.js | 692 ++++ .../h5p/editor/scripts/h5peditor-boolean.js | 86 + .../editor/scripts/h5peditor-coordinates.js | 194 ++ .../editor/scripts/h5peditor-dimensions.js | 174 + .../h5p/editor/scripts/h5peditor-editor.js | 616 ++++ .../editor/scripts/h5peditor-file-uploader.js | 131 + .../h5p/editor/scripts/h5peditor-file.js | 310 ++ .../h5p/editor/scripts/h5peditor-form.js | 451 +++ .../scripts/h5peditor-fullscreen-bar.js | 89 + .../h5p/editor/scripts/h5peditor-group.js | 402 +++ .../h5p/editor/scripts/h5peditor-html.js | 529 +++ .../editor/scripts/h5peditor-image-popup.js | 406 +++ .../h5p/editor/scripts/h5peditor-image.js | 306 ++ .../h5p/editor/scripts/h5peditor-init.js | 105 + .../scripts/h5peditor-library-list-cache.js | 117 + .../scripts/h5peditor-library-selector.js | 340 ++ .../h5p/editor/scripts/h5peditor-library.js | 614 ++++ .../editor/scripts/h5peditor-list-editor.js | 386 +++ .../h5p/editor/scripts/h5peditor-list.js | 345 ++ .../h5peditor-metadata-author-widget.js | 159 + .../h5peditor-metadata-changelog-widget.js | 274 ++ .../h5p/editor/scripts/h5peditor-metadata.js | 427 +++ .../h5p/editor/scripts/h5peditor-none.js | 50 + .../h5p/editor/scripts/h5peditor-number.js | 162 + .../h5p/editor/scripts/h5peditor-pre-save.js | 140 + .../h5p/editor/scripts/h5peditor-select.js | 134 + .../editor/scripts/h5peditor-selector-hub.js | 275 ++ .../scripts/h5peditor-selector-legacy.js | 114 + .../scripts/h5peditor-semantic-structure.js | 303 ++ .../h5p/editor/scripts/h5peditor-text.js | 124 + .../h5p/editor/scripts/h5peditor-textarea.js | 102 + .../h5p/editor/scripts/h5peditor.js | 1855 +++++++++++ .../static-assets/h5p/editor/styles/config.rb | 24 + .../h5p/editor/styles/css/application.css | 1 + .../h5p/editor/styles/css/fonts.css | 21 + .../styles/css/fonts/h5p-fullscreen-bar.eot | Bin 0 -> 6492 bytes .../styles/css/fonts/h5p-fullscreen-bar.svg | 42 + .../styles/css/fonts/h5p-fullscreen-bar.ttf | Bin 0 -> 6344 bytes .../styles/css/fonts/h5p-fullscreen-bar.woff | Bin 0 -> 6420 bytes .../h5p/editor/styles/css/fonts/h5p-hub.eot | Bin 0 -> 6172 bytes .../h5p/editor/styles/css/fonts/h5p-hub.svg | 46 + .../h5p/editor/styles/css/fonts/h5p-hub.ttf | Bin 0 -> 6008 bytes .../h5p/editor/styles/css/fonts/h5p-hub.woff | Bin 0 -> 6084 bytes .../styles/css/fonts/h5p-metadata-icons.eot | Bin 0 -> 5340 bytes .../styles/css/fonts/h5p-metadata-icons.svg | 31 + .../styles/css/fonts/h5p-metadata-icons.ttf | Bin 0 -> 5132 bytes .../styles/css/fonts/h5p-metadata-icons.woff | Bin 0 -> 5208 bytes .../h5p/editor/styles/css/h5p-hub-client.css | 1 + .../h5p/editor/styles/css/libs/icons.png | Bin 0 -> 494 bytes .../styles/css/libs/zebra_datepicker.min.css | 1 + .../h5p/editor/styles/scss/_copy-paste.scss | 93 + .../h5p/editor/styles/scss/_deprecated.scss | 13 + .../h5p/editor/styles/scss/_form-field.scss | 52 + .../h5p/editor/styles/scss/_form-groups.scss | 425 +++ .../editor/styles/scss/_fullscreen-bar.scss | 199 ++ .../scss/_h5peditor-image-edit-popup.scss | 149 + .../styles/scss/_h5peditor-image-edit.scss | 45 + .../styles/scss/_metadata-author-widget.scss | 102 + .../scss/_metadata-changelog-widget.scss | 128 + .../editor/styles/scss/_metadata-form.scss | 336 ++ .../editor/styles/scss/_metadata-popup.scss | 12 + .../h5p/editor/styles/scss/_mixins.scss | 17 + .../h5p/editor/styles/scss/_utils.scss | 5 + .../h5p/editor/styles/scss/_variables.scss | 57 + .../h5p/editor/styles/scss/application.scss | 1285 ++++++++ apps/server/static-assets/h5p/editor/v1.24.1 | 0 nest-cli.json | 2 +- 519 files changed, 47396 insertions(+), 117 deletions(-) create mode 100644 apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-ajax.api.spec.ts create mode 100644 apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-delete.api.spec.ts create mode 100644 apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-files.api.spec.ts create mode 100644 apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-get-editor.api.spec.ts create mode 100644 apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-get-player.api.spec.ts create mode 100644 apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-save-create.api.spec.ts delete mode 100644 apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor.api.spec.ts create mode 100644 apps/server/src/modules/h5p-editor/controller/dto/ajax/get.params.ts create mode 100644 apps/server/src/modules/h5p-editor/controller/dto/ajax/index.ts create mode 100644 apps/server/src/modules/h5p-editor/controller/dto/ajax/post.body.params.ts create mode 100644 apps/server/src/modules/h5p-editor/controller/dto/ajax/post.params.ts create mode 100644 apps/server/src/modules/h5p-editor/controller/dto/content-file.url.params.ts create mode 100644 apps/server/src/modules/h5p-editor/controller/dto/h5p-editor.params.ts create mode 100644 apps/server/src/modules/h5p-editor/controller/dto/index.ts create mode 100644 apps/server/src/modules/h5p-editor/controller/dto/library-file.url.params.ts create mode 100644 apps/server/src/modules/h5p-editor/service/h5p-ajax-endpoint.service.ts create mode 100644 apps/server/src/modules/h5p-editor/service/h5p-editor.service.ts create mode 100644 apps/server/src/modules/h5p-editor/service/h5p-player.service.ts create mode 100644 apps/server/src/modules/h5p-editor/service/index.ts create mode 100644 apps/server/src/modules/h5p-editor/uc/h5p-ajax.uc.spec.ts create mode 100644 apps/server/src/modules/h5p-editor/uc/h5p-delete.uc.spec.ts create mode 100644 apps/server/src/modules/h5p-editor/uc/h5p-files.uc.spec.ts create mode 100644 apps/server/src/modules/h5p-editor/uc/h5p-get-editor.uc.spec.ts create mode 100644 apps/server/src/modules/h5p-editor/uc/h5p-get-player.uc.spec.ts create mode 100644 apps/server/src/modules/h5p-editor/uc/h5p-save-create.uc.spec.ts create mode 100644 apps/server/src/modules/h5p-editor/uc/h5p.uc.ts create mode 100644 apps/server/static-assets/h5p/core/LICENSE.txt create mode 100644 apps/server/static-assets/h5p/core/README.txt create mode 100644 apps/server/static-assets/h5p/core/doc/spec_en.html create mode 100644 apps/server/static-assets/h5p/core/fonts/h5p-core-23.eot create mode 100644 apps/server/static-assets/h5p/core/fonts/h5p-core-23.svg create mode 100644 apps/server/static-assets/h5p/core/fonts/h5p-core-23.ttf create mode 100644 apps/server/static-assets/h5p/core/fonts/h5p-core-23.woff create mode 100644 apps/server/static-assets/h5p/core/images/h5p.svg create mode 100644 apps/server/static-assets/h5p/core/images/throbber.gif create mode 100644 apps/server/static-assets/h5p/core/js/h5p-action-bar.js create mode 100644 apps/server/static-assets/h5p/core/js/h5p-confirmation-dialog.js create mode 100644 apps/server/static-assets/h5p/core/js/h5p-content-type.js create mode 100644 apps/server/static-assets/h5p/core/js/h5p-content-upgrade-process.js create mode 100644 apps/server/static-assets/h5p/core/js/h5p-content-upgrade-worker.js create mode 100644 apps/server/static-assets/h5p/core/js/h5p-content-upgrade.js create mode 100644 apps/server/static-assets/h5p/core/js/h5p-data-view.js create mode 100644 apps/server/static-assets/h5p/core/js/h5p-display-options.js create mode 100644 apps/server/static-assets/h5p/core/js/h5p-embed.js create mode 100644 apps/server/static-assets/h5p/core/js/h5p-event-dispatcher.js create mode 100644 apps/server/static-assets/h5p/core/js/h5p-library-details.js create mode 100644 apps/server/static-assets/h5p/core/js/h5p-library-list.js create mode 100644 apps/server/static-assets/h5p/core/js/h5p-resizer.js create mode 100644 apps/server/static-assets/h5p/core/js/h5p-utils.js create mode 100644 apps/server/static-assets/h5p/core/js/h5p-version.js create mode 100644 apps/server/static-assets/h5p/core/js/h5p-x-api-event.js create mode 100644 apps/server/static-assets/h5p/core/js/h5p-x-api.js create mode 100644 apps/server/static-assets/h5p/core/js/h5p.js create mode 100644 apps/server/static-assets/h5p/core/js/jquery.js create mode 100644 apps/server/static-assets/h5p/core/js/request-queue.js create mode 100644 apps/server/static-assets/h5p/core/js/settings/h5p-disable-hub.js create mode 100644 apps/server/static-assets/h5p/core/styles/h5p-admin.css create mode 100644 apps/server/static-assets/h5p/core/styles/h5p-confirmation-dialog.css create mode 100644 apps/server/static-assets/h5p/core/styles/h5p-core-button.css create mode 100644 apps/server/static-assets/h5p/core/styles/h5p.css create mode 100644 apps/server/static-assets/h5p/core/v1.24.0 create mode 100644 apps/server/static-assets/h5p/editor/README.md create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/CHANGES.md create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/LICENSE.md create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/adapters/jquery.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/build-config.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/ckeditor.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/config.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/contents.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/af.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/ar.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/az.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/bg.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/bn.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/bs.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/ca.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/cs.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/cy.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/da.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/de-ch.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/de.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/el.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/en-au.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/en-ca.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/en-gb.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/en.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/eo.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/es-mx.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/es.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/et.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/eu.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/fa.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/fi.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/fo.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/fr-ca.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/fr.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/gl.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/gu.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/he.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/hi.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/hr.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/hu.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/id.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/is.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/it.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/ja.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/ka.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/km.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/ko.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/ku.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/lt.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/lv.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/mk.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/mn.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/ms.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/nb.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/nl.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/no.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/oc.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/pl.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/pt-br.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/pt.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/ro.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/ru.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/si.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/sk.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/sl.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/sq.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/sr-latn.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/sr.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/sv.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/th.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/tr.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/tt.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/ug.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/uk.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/vi.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/zh-cn.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/lang/zh.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/a11yhelp.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/_translationstatus.txt create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/af.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/ar.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/az.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/bg.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/ca.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/cs.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/cy.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/da.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/de-ch.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/de.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/el.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/en-au.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/en-gb.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/en.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/eo.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/es-mx.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/es.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/et.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/eu.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/fa.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/fi.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/fo.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/fr-ca.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/fr.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/gl.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/gu.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/he.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/hi.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/hr.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/hu.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/id.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/it.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/ja.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/km.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/ko.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/ku.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/lt.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/lv.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/mk.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/mn.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/nb.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/nl.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/no.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/oc.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/pl.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/pt-br.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/pt.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/ro.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/ru.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/si.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/sk.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/sl.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/sq.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/sr-latn.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/sr.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/sv.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/th.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/tr.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/tt.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/ug.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/uk.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/vi.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/zh-cn.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/a11yhelp/dialogs/lang/zh.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/clipboard/dialogs/paste.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/colordialog/dialogs/colordialog.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/colordialog/dialogs/colordialog.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/dialog/dialogDefinition.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/icons.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/icons_hidpi.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/lineheight/LICENSE create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/lineheight/README.md create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/lineheight/readme.txt create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/link/dialogs/anchor.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/link/dialogs/link.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/link/images/anchor.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/link/images/hidpi/anchor.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/magicline/images/hidpi/icon-rtl.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/magicline/images/hidpi/icon.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/magicline/images/icon-rtl.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/magicline/images/icon.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/pastefromword/filter/default.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/removeRedundantNBSP/plugin.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/_translationstatus.txt create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/af.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/ar.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/az.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/bg.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/ca.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/cs.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/cy.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/da.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/de-ch.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/de.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/el.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/en-au.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/en-ca.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/en-gb.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/en.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/eo.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/es-mx.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/es.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/et.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/eu.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/fa.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/fi.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/fr-ca.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/fr.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/gl.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/he.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/hr.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/hu.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/id.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/it.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/ja.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/km.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/ko.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/ku.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/lt.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/lv.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/nb.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/nl.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/no.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/oc.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/pl.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/pt-br.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/pt.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/ro.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/ru.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/si.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/sk.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/sl.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/sq.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/sr-latn.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/sr.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/sv.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/th.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/tr.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/tt.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/ug.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/uk.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/vi.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/zh-cn.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/lang/zh.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/specialchar/dialogs/specialchar.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/table/dialogs/table.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/plugins/tabletools/dialogs/tableCell.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/css/samples.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/img/github-top.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/img/header-bg.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/img/header-separator.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/img/logo.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/img/logo.svg create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/img/navigation-tip.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/index.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/js/sample.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/js/sf.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/ajax.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/api.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/appendto.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/assets/inlineall/logo.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/assets/outputxhtml/outputxhtml.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/assets/posteddata.php create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/assets/sample.jpg create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/assets/uilanguages/languages.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/autogrow/autogrow.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/datafiltering.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/dialog/assets/my_dialog.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/dialog/dialog.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/divreplace.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/enterkey/enterkey.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/htmlwriter/assets/outputforflash/outputforflash.fla create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/htmlwriter/assets/outputforflash/outputforflash.swf create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/htmlwriter/assets/outputforflash/swfobject.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/htmlwriter/outputforflash.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/htmlwriter/outputhtml.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/index.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/inlineall.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/inlinebycode.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/inlinetextarea.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/jquery.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/magicline/magicline.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/readonly.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/replacebyclass.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/replacebycode.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/sample.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/sample.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/sample_posteddata.php create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/tabindex.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/toolbar/toolbar.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/uicolor.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/uilanguages.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/wysiwygarea/fullpage.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/old/xhtmlstyle.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/toolbarconfigurator/css/fontello.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/toolbarconfigurator/font/LICENSE.txt create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/toolbarconfigurator/font/config.json create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/toolbarconfigurator/font/fontello.eot create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/toolbarconfigurator/font/fontello.svg create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/toolbarconfigurator/font/fontello.ttf create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/toolbarconfigurator/font/fontello.woff create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/toolbarconfigurator/index.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/toolbarconfigurator/js/abstracttoolbarmodifier.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/toolbarconfigurator/js/fulltoolbareditor.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/toolbarconfigurator/js/toolbarmodifier.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/samples/toolbarconfigurator/js/toolbartextmodifier.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/.temp/css/dialog.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/.temp/css/dialog_ie.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/.temp/css/dialog_ie7.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/.temp/css/dialog_ie8.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/.temp/css/dialog_iequirks.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/.temp/css/dialog_opera.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/.temp/css/editor.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/.temp/css/editor_gecko.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/.temp/css/editor_ie.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/.temp/css/editor_ie7.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/.temp/css/editor_ie8.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/.temp/css/editor_iequirks.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/dialog.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/dialog_ie.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/dialog_ie7.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/dialog_ie8.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/dialog_iequirks.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/dialog_opera.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/editor.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/editor_gecko.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/editor_ie.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/editor_ie7.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/editor_ie8.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/editor_iequirks.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/icons.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/icons_hidpi.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/images/arrow.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/images/close.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/images/hidpi/close.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/images/hidpi/lock-open.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/images/hidpi/lock.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/images/hidpi/refresh.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/images/lock-open.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/images/lock.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/images/refresh.png create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/readme.md create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/sample/bootstrapck-sample.html create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/sample/css/bootstrapck-sample.css create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/sample/js/analytics.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/sample/js/jquery-1.11.0.min.js create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/browser-specific/gecko/editor_gecko.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/browser-specific/ie/dialog_ie.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/browser-specific/ie/editor_ie.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/browser-specific/ie7/dialog_ie7.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/browser-specific/ie7/editor_ie7.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/browser-specific/ie8/dialog_ie8.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/browser-specific/ie8/editor_ie8.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/browser-specific/iequirks/dialog_iequirks.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/browser-specific/iequirks/editor_iequirks.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/browser-specific/opera/dialog_opera.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/components/_colorpanel.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/components/_elementspath.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/components/_mainui.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/components/_menu.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/components/_panel.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/components/_presets.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/components/_reset.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/components/_richcombo.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/components/_toolbar.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/components/editor.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/config/_colors.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/config/_config.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/config/_defaults.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/skins/bootstrapck/scss/dialog/dialog.scss create mode 100644 apps/server/static-assets/h5p/editor/ckeditor/styles.js create mode 100644 apps/server/static-assets/h5p/editor/composer.json create mode 100644 apps/server/static-assets/h5p/editor/images/add.png create mode 100644 apps/server/static-assets/h5p/editor/images/binary-file.png create mode 100644 apps/server/static-assets/h5p/editor/images/collapse.png create mode 100644 apps/server/static-assets/h5p/editor/images/down.png create mode 100644 apps/server/static-assets/h5p/editor/images/expand.png create mode 100644 apps/server/static-assets/h5p/editor/images/order.png create mode 100644 apps/server/static-assets/h5p/editor/images/remove.png create mode 100644 apps/server/static-assets/h5p/editor/images/transparent-background.png create mode 100644 apps/server/static-assets/h5p/editor/images/webm-file.png create mode 100644 apps/server/static-assets/h5p/editor/language/ar.js create mode 100644 apps/server/static-assets/h5p/editor/language/bs.js create mode 100644 apps/server/static-assets/h5p/editor/language/de.js create mode 100644 apps/server/static-assets/h5p/editor/language/el.js create mode 100644 apps/server/static-assets/h5p/editor/language/en.js create mode 100644 apps/server/static-assets/h5p/editor/language/es-cr.js create mode 100644 apps/server/static-assets/h5p/editor/language/es-mx.js create mode 100644 apps/server/static-assets/h5p/editor/language/es.js create mode 100644 apps/server/static-assets/h5p/editor/language/et.js create mode 100644 apps/server/static-assets/h5p/editor/language/eu.js create mode 100644 apps/server/static-assets/h5p/editor/language/fi.js create mode 100644 apps/server/static-assets/h5p/editor/language/fr.js create mode 100644 apps/server/static-assets/h5p/editor/language/it.js create mode 100644 apps/server/static-assets/h5p/editor/language/nb.js create mode 100644 apps/server/static-assets/h5p/editor/language/nl.js create mode 100644 apps/server/static-assets/h5p/editor/language/nn.js create mode 100644 apps/server/static-assets/h5p/editor/language/pl.js create mode 100644 apps/server/static-assets/h5p/editor/language/pt-br.js create mode 100644 apps/server/static-assets/h5p/editor/language/pt.js create mode 100644 apps/server/static-assets/h5p/editor/language/ru.js create mode 100644 apps/server/static-assets/h5p/editor/language/tr.js create mode 100644 apps/server/static-assets/h5p/editor/libs/darkroom.css create mode 100644 apps/server/static-assets/h5p/editor/libs/darkroom.js create mode 100644 apps/server/static-assets/h5p/editor/libs/fabric.js create mode 100644 apps/server/static-assets/h5p/editor/libs/zebra_datepicker.min.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5p-hub-client.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-av.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-boolean.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-coordinates.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-dimensions.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-editor.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-file-uploader.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-file.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-form.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-fullscreen-bar.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-group.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-html.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-image-popup.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-image.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-init.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-library-list-cache.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-library-selector.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-library.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-list-editor.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-list.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-metadata-author-widget.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-metadata-changelog-widget.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-metadata.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-none.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-number.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-pre-save.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-select.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-selector-hub.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-selector-legacy.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-semantic-structure.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-text.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor-textarea.js create mode 100644 apps/server/static-assets/h5p/editor/scripts/h5peditor.js create mode 100644 apps/server/static-assets/h5p/editor/styles/config.rb create mode 100644 apps/server/static-assets/h5p/editor/styles/css/application.css create mode 100644 apps/server/static-assets/h5p/editor/styles/css/fonts.css create mode 100644 apps/server/static-assets/h5p/editor/styles/css/fonts/h5p-fullscreen-bar.eot create mode 100644 apps/server/static-assets/h5p/editor/styles/css/fonts/h5p-fullscreen-bar.svg create mode 100644 apps/server/static-assets/h5p/editor/styles/css/fonts/h5p-fullscreen-bar.ttf create mode 100644 apps/server/static-assets/h5p/editor/styles/css/fonts/h5p-fullscreen-bar.woff create mode 100644 apps/server/static-assets/h5p/editor/styles/css/fonts/h5p-hub.eot create mode 100644 apps/server/static-assets/h5p/editor/styles/css/fonts/h5p-hub.svg create mode 100644 apps/server/static-assets/h5p/editor/styles/css/fonts/h5p-hub.ttf create mode 100644 apps/server/static-assets/h5p/editor/styles/css/fonts/h5p-hub.woff create mode 100644 apps/server/static-assets/h5p/editor/styles/css/fonts/h5p-metadata-icons.eot create mode 100644 apps/server/static-assets/h5p/editor/styles/css/fonts/h5p-metadata-icons.svg create mode 100644 apps/server/static-assets/h5p/editor/styles/css/fonts/h5p-metadata-icons.ttf create mode 100644 apps/server/static-assets/h5p/editor/styles/css/fonts/h5p-metadata-icons.woff create mode 100644 apps/server/static-assets/h5p/editor/styles/css/h5p-hub-client.css create mode 100644 apps/server/static-assets/h5p/editor/styles/css/libs/icons.png create mode 100644 apps/server/static-assets/h5p/editor/styles/css/libs/zebra_datepicker.min.css create mode 100644 apps/server/static-assets/h5p/editor/styles/scss/_copy-paste.scss create mode 100644 apps/server/static-assets/h5p/editor/styles/scss/_deprecated.scss create mode 100644 apps/server/static-assets/h5p/editor/styles/scss/_form-field.scss create mode 100644 apps/server/static-assets/h5p/editor/styles/scss/_form-groups.scss create mode 100644 apps/server/static-assets/h5p/editor/styles/scss/_fullscreen-bar.scss create mode 100644 apps/server/static-assets/h5p/editor/styles/scss/_h5peditor-image-edit-popup.scss create mode 100644 apps/server/static-assets/h5p/editor/styles/scss/_h5peditor-image-edit.scss create mode 100644 apps/server/static-assets/h5p/editor/styles/scss/_metadata-author-widget.scss create mode 100644 apps/server/static-assets/h5p/editor/styles/scss/_metadata-changelog-widget.scss create mode 100644 apps/server/static-assets/h5p/editor/styles/scss/_metadata-form.scss create mode 100644 apps/server/static-assets/h5p/editor/styles/scss/_metadata-popup.scss create mode 100644 apps/server/static-assets/h5p/editor/styles/scss/_mixins.scss create mode 100644 apps/server/static-assets/h5p/editor/styles/scss/_utils.scss create mode 100644 apps/server/static-assets/h5p/editor/styles/scss/_variables.scss create mode 100644 apps/server/static-assets/h5p/editor/styles/scss/application.scss create mode 100644 apps/server/static-assets/h5p/editor/v1.24.1 diff --git a/apps/server/src/apps/h5p-editor.app.ts b/apps/server/src/apps/h5p-editor.app.ts index fcd550c34fa..0b249ecc192 100644 --- a/apps/server/src/apps/h5p-editor.app.ts +++ b/apps/server/src/apps/h5p-editor.app.ts @@ -7,6 +7,8 @@ import express from 'express'; // register source-map-support for debugging import { install as sourceMapInstall } from 'source-map-support'; +import path from 'node:path'; + // application imports import { LegacyLogger } from '@src/core/logger'; import { H5PEditorModule } from '@src/modules/h5p-editor'; @@ -19,6 +21,14 @@ async function bootstrap() { const nestExpress = express(); const nestExpressAdapter = new ExpressAdapter(nestExpress); + + const oneHourInMs = 1000 * 60 * 60; + + nestExpressAdapter.useStaticAssets(path.join(__dirname, '../static-assets/h5p'), { + prefix: '/h5p-editor', + maxAge: oneHourInMs, + }); + const nestApp = await NestFactory.create(H5PEditorModule, nestExpressAdapter); // WinstonLogger nestApp.useLogger(await nestApp.resolve(LegacyLogger)); diff --git a/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-ajax.api.spec.ts b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-ajax.api.spec.ts new file mode 100644 index 00000000000..ce3d01e05ec --- /dev/null +++ b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-ajax.api.spec.ts @@ -0,0 +1,172 @@ +import { DeepMocked, createMock } from '@golevelup/ts-jest'; +import { H5PAjaxEndpoint } from '@lumieducation/h5p-server'; +import { EntityManager } from '@mikro-orm/core'; +import { HttpStatus, INestApplication } from '@nestjs/common'; +import { Test } from '@nestjs/testing'; +import { TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; +import { H5PEditorTestModule } from '@src/modules/h5p-editor/h5p-editor-test.module'; + +describe('H5PEditor Controller (api)', () => { + let app: INestApplication; + let em: EntityManager; + let testApiClient: TestApiClient; + + let ajaxEndpoint: DeepMocked; + + beforeAll(async () => { + const module = await Test.createTestingModule({ + imports: [H5PEditorTestModule], + }) + .overrideProvider(H5PAjaxEndpoint) + .useValue(createMock()) + .compile(); + + app = module.createNestApplication(); + await app.init(); + em = app.get(EntityManager); + ajaxEndpoint = app.get(H5PAjaxEndpoint); + testApiClient = new TestApiClient(app, 'h5p-editor'); + }); + + afterEach(() => { + jest.resetAllMocks(); + }); + + afterAll(async () => { + await app.close(); + }); + + describe('when calling AJAX GET', () => { + describe('when user not exists', () => { + it('should respond with unauthorized exception', async () => { + const response = await testApiClient.get('ajax'); + + expect(response.statusCode).toEqual(HttpStatus.UNAUTHORIZED); + expect(response.body).toEqual({ + type: 'UNAUTHORIZED', + title: 'Unauthorized', + message: 'Unauthorized', + code: 401, + }); + }); + }); + + describe('when user is logged in', () => { + const createStudent = () => UserAndAccountTestFactory.buildStudent(); + + const setup = async () => { + const { studentAccount, studentUser } = createStudent(); + + await em.persistAndFlush([studentAccount, studentUser]); + em.clear(); + + const loggedInClient = await testApiClient.login(studentAccount); + + return { loggedInClient, studentUser }; + }; + + it('should call H5PAjaxEndpoint', async () => { + const { + loggedInClient, + studentUser: { id }, + } = await setup(); + + const dummyResponse = { + apiVersion: { major: 1, minor: 1 }, + details: [], + libraries: [], + outdated: false, + recentlyUsed: [], + user: 'DummyUser', + }; + + ajaxEndpoint.getAjax.mockResolvedValueOnce(dummyResponse); + + const response = await loggedInClient.get(`ajax?action=content-type-cache`); + + expect(response.statusCode).toEqual(HttpStatus.OK); + expect(response.body).toEqual(dummyResponse); + expect(ajaxEndpoint.getAjax).toHaveBeenCalledWith( + 'content-type-cache', + undefined, // MachineName + undefined, // MajorVersion + undefined, // MinorVersion + undefined, // Language + expect.objectContaining({ id }) + ); + }); + }); + + describe('when calling AJAX POST', () => { + describe('when user not exists', () => { + it('should respond with unauthorized exception', async () => { + const response = await testApiClient.post('ajax'); + + expect(response.statusCode).toEqual(HttpStatus.UNAUTHORIZED); + expect(response.body).toEqual({ + type: 'UNAUTHORIZED', + title: 'Unauthorized', + message: 'Unauthorized', + code: 401, + }); + }); + }); + + describe('when user is logged in', () => { + const createStudent = () => UserAndAccountTestFactory.buildStudent(); + + const setup = async () => { + const { studentAccount, studentUser } = createStudent(); + + await em.persistAndFlush([studentAccount, studentUser]); + em.clear(); + + const loggedInClient = await testApiClient.login(studentAccount); + + return { loggedInClient, studentUser }; + }; + + it('should call H5PAjaxEndpoint', async () => { + const { + loggedInClient, + studentUser: { id }, + } = await setup(); + + const dummyResponse = [ + { + majorVersion: 1, + minorVersion: 2, + metadataSettings: {}, + name: 'Dummy Library', + restricted: false, + runnable: true, + title: 'Dummy Library', + tutorialUrl: '', + uberName: 'dummyLibrary-1.1', + }, + ]; + + const dummyBody = { contentId: 'id', field: 'field', libraries: ['dummyLibrary-1.0'], libraryParameters: '' }; + + ajaxEndpoint.postAjax.mockResolvedValueOnce(dummyResponse); + + const response = await loggedInClient.post(`ajax?action=libraries`, dummyBody); + + expect(response.statusCode).toEqual(HttpStatus.CREATED); + expect(response.body).toEqual(dummyResponse); + expect(ajaxEndpoint.postAjax).toHaveBeenCalledWith( + 'libraries', + dummyBody, + undefined, + expect.objectContaining({ id }), + undefined, + undefined, + undefined, + undefined, + undefined + ); + }); + }); + }); + }); +}); diff --git a/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-delete.api.spec.ts b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-delete.api.spec.ts new file mode 100644 index 00000000000..71da033d89e --- /dev/null +++ b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-delete.api.spec.ts @@ -0,0 +1,100 @@ +import { JwtAuthGuard } from '@src/modules/authentication/guard/jwt-auth.guard'; +import request from 'supertest'; +import { EntityManager } from '@mikro-orm/mongodb'; +import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { Test } from '@nestjs/testing'; +import { Permission } from '@shared/domain'; +import { DeepMocked, createMock } from '@golevelup/ts-jest/lib/mocks'; +import { cleanupCollections, mapUserToCurrentUser, roleFactory, schoolFactory, userFactory } from '@shared/testing'; +import { ICurrentUser } from '@src/modules/authentication'; +import { Request } from 'express'; +import { H5PEditorTestModule } from '../../h5p-editor-test.module'; +import { H5PEditorUc } from '../../uc/h5p.uc'; + +class API { + constructor(private app: INestApplication) { + this.app = app; + } + + async deleteH5pContent(contentId: string) { + return request(this.app.getHttpServer()).post(`/h5p-editor/delete/${contentId}`); + } +} + +const setup = () => { + const contentId = '12345'; + const notExistingContentId = '12345'; + const badContentId = ''; + + return { contentId, notExistingContentId, badContentId }; +}; + +describe('H5PEditor Controller (api)', () => { + let app: INestApplication; + let api: API; + let em: EntityManager; + let currentUser: ICurrentUser; + let h5PEditorUc: DeepMocked; + + beforeAll(async () => { + const module = await Test.createTestingModule({ + imports: [H5PEditorTestModule], + }) + .overrideGuard(JwtAuthGuard) + .useValue({ + canActivate(context: ExecutionContext) { + const req: Request = context.switchToHttp().getRequest(); + req.user = currentUser; + return true; + }, + }) + .overrideProvider(H5PEditorUc) + .useValue(createMock()) + .compile(); + + app = module.createNestApplication(); + await app.init(); + h5PEditorUc = module.get(H5PEditorUc); + + api = new API(app); + em = module.get(EntityManager); + }); + + afterAll(async () => { + await app.close(); + }); + + describe('delete h5p content', () => { + beforeEach(async () => { + await cleanupCollections(em); + const school = schoolFactory.build(); + const roles = roleFactory.buildList(1, { + permissions: [Permission.FILESTORAGE_CREATE, Permission.FILESTORAGE_VIEW], + }); + const user = userFactory.build({ school, roles }); + + await em.persistAndFlush([user, school]); + em.clear(); + + currentUser = mapUserToCurrentUser(user); + }); + describe('with valid request params', () => { + it('should return 200 status', async () => { + const { contentId } = setup(); + + h5PEditorUc.deleteH5pContent.mockResolvedValueOnce(true); + const response = await api.deleteH5pContent(contentId); + expect(response.status).toEqual(201); + }); + }); + describe('with bad request params', () => { + it('should return 500 status', async () => { + const { notExistingContentId } = setup(); + + h5PEditorUc.deleteH5pContent.mockRejectedValueOnce(new Error('Could not delete H5P content')); + const response = await api.deleteH5pContent(notExistingContentId); + expect(response.status).toEqual(500); + }); + }); + }); +}); diff --git a/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-files.api.spec.ts b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-files.api.spec.ts new file mode 100644 index 00000000000..20c2c9ad5e7 --- /dev/null +++ b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-files.api.spec.ts @@ -0,0 +1,298 @@ +import { DeepMocked, createMock } from '@golevelup/ts-jest'; +import { ContentMetadata } from '@lumieducation/h5p-server/build/src/ContentMetadata'; +import { EntityManager } from '@mikro-orm/core'; +import { HttpStatus, INestApplication } from '@nestjs/common'; +import { Test } from '@nestjs/testing'; +import { TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; +import { H5PEditorTestModule } from '@src/modules/h5p-editor/h5p-editor-test.module'; +import { Readable } from 'stream'; +import { ContentStorage } from '../../contentStorage/contentStorage'; +import { LibraryStorage } from '../../libraryStorage/libraryStorage'; +import { TemporaryFileStorage } from '../../temporary-file-storage/temporary-file-storage'; + +describe('H5PEditor Controller (api)', () => { + let app: INestApplication; + let em: EntityManager; + let testApiClient: TestApiClient; + + let contentStorage: DeepMocked; + let libraryStorage: DeepMocked; + let temporaryStorage: DeepMocked; + + beforeAll(async () => { + const module = await Test.createTestingModule({ + imports: [H5PEditorTestModule], + }) + .overrideProvider(ContentStorage) + .useValue(createMock()) + .overrideProvider(LibraryStorage) + .useValue(createMock()) + .overrideProvider(TemporaryFileStorage) + .useValue(createMock()) + .compile(); + + app = module.createNestApplication(); + await app.init(); + em = app.get(EntityManager); + contentStorage = app.get(ContentStorage); + libraryStorage = app.get(LibraryStorage); + temporaryStorage = app.get(TemporaryFileStorage); + testApiClient = new TestApiClient(app, 'h5p-editor'); + }); + + afterAll(async () => { + await app.close(); + }); + + describe('when requesting library files', () => { + describe('when user not exists', () => { + it('should respond with unauthorized exception', async () => { + const response = await testApiClient.get('libraries/dummyLib/test.txt'); + + expect(response.statusCode).toEqual(HttpStatus.UNAUTHORIZED); + expect(response.body).toEqual({ + type: 'UNAUTHORIZED', + title: 'Unauthorized', + message: 'Unauthorized', + code: 401, + }); + }); + }); + + describe('when user is logged in', () => { + const createStudent = () => UserAndAccountTestFactory.buildStudent(); + + const setup = async () => { + const { studentAccount, studentUser } = createStudent(); + + await em.persistAndFlush([studentAccount, studentUser]); + em.clear(); + + const loggedInClient = await testApiClient.login(studentAccount); + + return { loggedInClient }; + }; + + it('should return the library file', async () => { + const { loggedInClient } = await setup(); + + const mockFile = { content: 'Test File', size: 9, name: 'test.txt', birthtime: new Date() }; + + libraryStorage.getFileStream.mockResolvedValueOnce(Readable.from(mockFile.content)); + libraryStorage.getFileStats.mockResolvedValueOnce({ birthtime: mockFile.birthtime, size: mockFile.size }); + + const response = await loggedInClient.get(`libraries/dummyLib-1.0/${mockFile.name}`); + + expect(response.statusCode).toEqual(HttpStatus.OK); + expect(response.text).toBe(mockFile.content); + }); + + it('should return 404 if file does not exist', async () => { + const { loggedInClient } = await setup(); + + libraryStorage.getFileStats.mockRejectedValueOnce(new Error('Does not exist')); + + const response = await loggedInClient.get(`libraries/dummyLib-1.0/nonexistant.txt`); + + expect(response.statusCode).toEqual(HttpStatus.NOT_FOUND); + }); + }); + }); + + describe('when requesting content files', () => { + describe('when user not exists', () => { + it('should respond with unauthorized exception', async () => { + const response = await testApiClient.get('content/dummyId/test.txt'); + + expect(response.statusCode).toEqual(HttpStatus.UNAUTHORIZED); + expect(response.body).toEqual({ + type: 'UNAUTHORIZED', + title: 'Unauthorized', + message: 'Unauthorized', + code: 401, + }); + }); + }); + + describe('when user is logged in', () => { + const createStudent = () => UserAndAccountTestFactory.buildStudent(); + + const setup = async () => { + const { studentAccount, studentUser } = createStudent(); + + await em.persistAndFlush([studentAccount, studentUser]); + em.clear(); + + const loggedInClient = await testApiClient.login(studentAccount); + + return { loggedInClient }; + }; + + it('should return the content file', async () => { + const { loggedInClient } = await setup(); + + const mockFile = { content: 'Test File', size: 9, name: 'test.txt', birthtime: new Date() }; + + contentStorage.getFileStream.mockResolvedValueOnce(Readable.from(mockFile.content)); + contentStorage.getFileStats.mockResolvedValueOnce({ birthtime: mockFile.birthtime, size: mockFile.size }); + + const response = await loggedInClient.get(`content/dummyId/${mockFile.name}`); + + expect(response.statusCode).toEqual(HttpStatus.OK); + expect(response.text).toBe(mockFile.content); + }); + + it('should work with range requests', async () => { + const { loggedInClient } = await setup(); + + const mockFile = { content: 'Test File', size: 9, name: 'test.txt', birthtime: new Date() }; + + contentStorage.getFileStream.mockResolvedValueOnce(Readable.from(mockFile.content)); + contentStorage.getFileStats.mockResolvedValueOnce({ birthtime: mockFile.birthtime, size: mockFile.size }); + + const response = await loggedInClient.get(`content/dummyId/${mockFile.name}`).set('Range', 'bytes=2-4'); + + expect(response.statusCode).toEqual(HttpStatus.PARTIAL_CONTENT); + expect(response.text).toBe(mockFile.content); + }); + + it('should return 404 if file does not exist', async () => { + const { loggedInClient } = await setup(); + + contentStorage.getFileStats.mockRejectedValueOnce(new Error('Does not exist')); + + const response = await loggedInClient.get(`content/dummyId/nonexistant.txt`); + + expect(response.statusCode).toEqual(HttpStatus.NOT_FOUND); + }); + }); + }); + + describe('when requesting temporary files', () => { + describe('when user not exists', () => { + it('should respond with unauthorized exception', async () => { + const response = await testApiClient.get('temp-files/test.txt'); + + expect(response.statusCode).toEqual(HttpStatus.UNAUTHORIZED); + expect(response.body).toEqual({ + type: 'UNAUTHORIZED', + title: 'Unauthorized', + message: 'Unauthorized', + code: 401, + }); + }); + }); + + describe('when user is logged in', () => { + const createStudent = () => UserAndAccountTestFactory.buildStudent(); + + const setup = async () => { + const { studentAccount, studentUser } = createStudent(); + + await em.persistAndFlush([studentAccount, studentUser]); + em.clear(); + + const loggedInClient = await testApiClient.login(studentAccount); + + return { loggedInClient }; + }; + + it('should return the content file', async () => { + const { loggedInClient } = await setup(); + + const mockFile = { content: 'Test File', size: 9, name: 'test.txt', birthtime: new Date() }; + + temporaryStorage.getFileStream.mockResolvedValueOnce(Readable.from(mockFile.content)); + temporaryStorage.getFileStats.mockResolvedValueOnce({ birthtime: mockFile.birthtime, size: mockFile.size }); + + const response = await loggedInClient.get(`temp-files/${mockFile.name}`); + + expect(response.statusCode).toEqual(HttpStatus.OK); + expect(response.text).toBe(mockFile.content); + }); + + it('should work with range requests', async () => { + const { loggedInClient } = await setup(); + + const mockFile = { content: 'Test File', size: 9, name: 'test.txt', birthtime: new Date() }; + + temporaryStorage.getFileStream.mockResolvedValueOnce(Readable.from(mockFile.content)); + temporaryStorage.getFileStats.mockResolvedValueOnce({ birthtime: mockFile.birthtime, size: mockFile.size }); + + const response = await loggedInClient.get(`temp-files/${mockFile.name}`).set('Range', 'bytes=2-4'); + + expect(response.statusCode).toEqual(HttpStatus.PARTIAL_CONTENT); + expect(response.text).toBe(mockFile.content); + }); + + it('should return 404 if file does not exist', async () => { + const { loggedInClient } = await setup(); + + temporaryStorage.getFileStats.mockRejectedValueOnce(new Error('Does not exist')); + + const response = await loggedInClient.get(`temp-files/nonexistant.txt`); + + expect(response.statusCode).toEqual(HttpStatus.NOT_FOUND); + }); + }); + }); + + describe('when requesting content parameters', () => { + describe('when user not exists', () => { + it('should respond with unauthorized exception', async () => { + const response = await testApiClient.get('params/dummyId'); + + expect(response.statusCode).toEqual(HttpStatus.UNAUTHORIZED); + expect(response.body).toEqual({ + type: 'UNAUTHORIZED', + title: 'Unauthorized', + message: 'Unauthorized', + code: 401, + }); + }); + }); + + describe('when user is logged in', () => { + const createStudent = () => UserAndAccountTestFactory.buildStudent(); + + const setup = async () => { + const { studentAccount, studentUser } = createStudent(); + + await em.persistAndFlush([studentAccount, studentUser]); + em.clear(); + + const loggedInClient = await testApiClient.login(studentAccount); + + return { loggedInClient }; + }; + + it('should return the content parameters', async () => { + const { loggedInClient } = await setup(); + + const dummyMetadata = new ContentMetadata(); + const dummyParams = { name: 'Dummy' }; + + contentStorage.getMetadata.mockResolvedValueOnce(dummyMetadata); + contentStorage.getParameters.mockResolvedValueOnce(dummyParams); + + const response = await loggedInClient.get(`params/dummyId`); + + expect(response.statusCode).toEqual(HttpStatus.OK); + expect(response.body).toEqual({ + h5p: dummyMetadata, + params: { metadata: dummyMetadata, params: dummyParams }, + }); + }); + + it('should return 404 if content does not exist', async () => { + const { loggedInClient } = await setup(); + + contentStorage.getMetadata.mockRejectedValueOnce(new Error('Does not exist')); + + const response = await loggedInClient.get('params/dummyId'); + + expect(response.statusCode).toEqual(HttpStatus.NOT_FOUND); + }); + }); + }); +}); diff --git a/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-get-editor.api.spec.ts b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-get-editor.api.spec.ts new file mode 100644 index 00000000000..2d52db9c16d --- /dev/null +++ b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-get-editor.api.spec.ts @@ -0,0 +1,98 @@ +import { JwtAuthGuard } from '@src/modules/authentication/guard/jwt-auth.guard'; +import request from 'supertest'; +import { EntityManager } from '@mikro-orm/mongodb'; +import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { Test } from '@nestjs/testing'; +import { Permission } from '@shared/domain'; +import { cleanupCollections, mapUserToCurrentUser, roleFactory, schoolFactory, userFactory } from '@shared/testing'; +import { ICurrentUser } from '@src/modules/authentication'; +import { Request } from 'express'; +import { DeepMocked, createMock } from '@golevelup/ts-jest/lib/mocks'; +import { H5PEditorTestModule } from '../../h5p-editor-test.module'; +import { H5PEditorUc } from '../../uc/h5p.uc'; + +class API { + constructor(private app: INestApplication) { + this.app = app; + } + + async editH5pContent(contentId: string) { + return request(this.app.getHttpServer()).get(`/h5p-editor/${contentId}`); + } +} + +const setup = () => { + const contentId = '12345'; + const notExistingContentId = '12345'; + const badContentId = ''; + + return { contentId, notExistingContentId, badContentId }; +}; + +describe('H5PEditor Controller (api)', () => { + let app: INestApplication; + let api: API; + let em: EntityManager; + let currentUser: ICurrentUser; + let h5PEditorUc: DeepMocked; + + beforeAll(async () => { + const module = await Test.createTestingModule({ + imports: [H5PEditorTestModule], + }) + .overrideGuard(JwtAuthGuard) + .useValue({ + canActivate(context: ExecutionContext) { + const req: Request = context.switchToHttp().getRequest(); + req.user = currentUser; + return true; + }, + }) + .overrideProvider(H5PEditorUc) + .useValue(createMock()) + .compile(); + + app = module.createNestApplication(); + await app.init(); + h5PEditorUc = module.get(H5PEditorUc); + + api = new API(app); + em = module.get(EntityManager); + }); + + afterAll(async () => { + await app.close(); + }); + + describe('get h5p editor', () => { + beforeEach(async () => { + await cleanupCollections(em); + const school = schoolFactory.build(); + const roles = roleFactory.buildList(1, { + permissions: [Permission.FILESTORAGE_CREATE, Permission.FILESTORAGE_VIEW], + }); + const user = userFactory.build({ school, roles }); + + await em.persistAndFlush([user, school]); + em.clear(); + + currentUser = mapUserToCurrentUser(user); + }); + describe('with valid request params', () => { + it('should return 200 status', async () => { + const { contentId } = setup(); + h5PEditorUc.getH5pEditor.mockResolvedValueOnce('iFrame'); + const response = await api.editH5pContent(contentId); + expect(response.status).toEqual(200); + }); + }); + describe('with bad request params', () => { + it('should return 500 status', async () => { + const { notExistingContentId } = setup(); + h5PEditorUc.getH5pEditor.mockRejectedValueOnce(new Error('Could not get H5P editor')); + const response = await api.editH5pContent(notExistingContentId); + expect(response.status).toEqual(500); + }); + }); + }); +}); diff --git a/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-get-player.api.spec.ts b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-get-player.api.spec.ts new file mode 100644 index 00000000000..0cfb7dd3070 --- /dev/null +++ b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-get-player.api.spec.ts @@ -0,0 +1,97 @@ +import { JwtAuthGuard } from '@src/modules/authentication/guard/jwt-auth.guard'; +import request from 'supertest'; +import { EntityManager } from '@mikro-orm/mongodb'; +import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { Test } from '@nestjs/testing'; +import { Permission } from '@shared/domain'; +import { cleanupCollections, mapUserToCurrentUser, roleFactory, schoolFactory, userFactory } from '@shared/testing'; +import { ICurrentUser } from '@src/modules/authentication'; +import { Request } from 'express'; +import { DeepMocked, createMock } from '@golevelup/ts-jest/lib/mocks'; +import { H5PEditorTestModule } from '../../h5p-editor-test.module'; +import { H5PEditorUc } from '../../uc/h5p.uc'; + +class API { + constructor(private app: INestApplication) { + this.app = app; + } + + async getPlayer(contentId: string) { + return request(this.app.getHttpServer()).get(`/h5p-editor/play/${contentId}`); + } +} + +const setup = () => { + const contentId = '12345'; + const notExistingContentId = '12345'; + + return { contentId, notExistingContentId }; +}; + +describe('H5PEditor Controller (api)', () => { + let app: INestApplication; + let api: API; + let em: EntityManager; + let currentUser: ICurrentUser; + let h5PEditorUc: DeepMocked; + + beforeAll(async () => { + const module = await Test.createTestingModule({ + imports: [H5PEditorTestModule], + }) + .overrideGuard(JwtAuthGuard) + .useValue({ + canActivate(context: ExecutionContext) { + const req: Request = context.switchToHttp().getRequest(); + req.user = currentUser; + return true; + }, + }) + .overrideProvider(H5PEditorUc) + .useValue(createMock()) + .compile(); + + app = module.createNestApplication(); + h5PEditorUc = module.get(H5PEditorUc); + await app.init(); + + api = new API(app); + em = module.get(EntityManager); + }); + + afterAll(async () => { + await app.close(); + }); + + describe('get h5p player', () => { + beforeEach(async () => { + await cleanupCollections(em); + const school = schoolFactory.build(); + const roles = roleFactory.buildList(1, { + permissions: [Permission.FILESTORAGE_CREATE, Permission.FILESTORAGE_VIEW], + }); + const user = userFactory.build({ school, roles }); + + await em.persistAndFlush([user, school]); + em.clear(); + + currentUser = mapUserToCurrentUser(user); + }); + describe('with valid request params', () => { + it('should return 200 status', async () => { + const { contentId } = setup(); + h5PEditorUc.getH5pPlayer.mockResolvedValueOnce('iFrame'); + const response = await api.getPlayer(contentId); + expect(response.status).toEqual(200); + }); + }); + describe('with bad request params', () => { + it('should return 500 status', async () => { + const { notExistingContentId } = setup(); + h5PEditorUc.getH5pPlayer.mockRejectedValueOnce(new Error('Could not get H5P player')); + const response = await api.getPlayer(notExistingContentId); + expect(response.status).toEqual(500); + }); + }); + }); +}); diff --git a/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-save-create.api.spec.ts b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-save-create.api.spec.ts new file mode 100644 index 00000000000..90804c343c6 --- /dev/null +++ b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-save-create.api.spec.ts @@ -0,0 +1,143 @@ +import { JwtAuthGuard } from '@src/modules/authentication/guard/jwt-auth.guard'; +import request from 'supertest'; +import { EntityManager } from '@mikro-orm/mongodb'; +import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { Test } from '@nestjs/testing'; +import { Permission } from '@shared/domain'; +import { cleanupCollections, mapUserToCurrentUser, roleFactory, schoolFactory, userFactory } from '@shared/testing'; +import { ICurrentUser } from '@src/modules/authentication'; +import { Request } from 'express'; +import { IContentMetadata } from '@lumieducation/h5p-server'; +import { DeepMocked, createMock } from '@golevelup/ts-jest/lib/mocks'; +import { H5PEditorTestModule } from '../../h5p-editor-test.module'; +import { H5PEditorUc } from '../../uc/h5p.uc'; + +const setup = () => { + const contentId = '12345'; + const createContentId = 'create'; + const notExistingContentId = '12345'; + const badContentId = ''; + const id = '0000000'; + const metadata: IContentMetadata = { + embedTypes: [], + language: 'de', + mainLibrary: 'mainLib', + preloadedDependencies: [], + defaultLanguage: '', + license: '', + title: '123', + }; + + return { contentId, notExistingContentId, badContentId, createContentId, id, metadata }; +}; + +class API { + constructor(private app: INestApplication) { + this.app = app; + } + + async createOrSave(contentId: string) { + const body = { + params: { + params: {}, + metadata: {}, + }, + metadata: {}, + library: {}, + }; + return request(this.app.getHttpServer()).post(`/h5p-editor/${contentId}`).send(body); + } +} + +describe('H5PEditor Controller (api)', () => { + let app: INestApplication; + let api: API; + let em: EntityManager; + let currentUser: ICurrentUser; + let h5PEditorUc: DeepMocked; + + beforeAll(async () => { + const module = await Test.createTestingModule({ + imports: [H5PEditorTestModule], + }) + .overrideGuard(JwtAuthGuard) + .useValue({ + canActivate(context: ExecutionContext) { + const req: Request = context.switchToHttp().getRequest(); + req.user = currentUser; + return true; + }, + }) + .overrideProvider(H5PEditorUc) + .useValue(createMock()) + .compile(); + + app = module.createNestApplication(); + await app.init(); + h5PEditorUc = module.get(H5PEditorUc); + + api = new API(app); + em = module.get(EntityManager); + }); + + afterAll(async () => { + await app.close(); + }); + + describe('create h5p content', () => { + beforeEach(async () => { + await cleanupCollections(em); + const school = schoolFactory.build(); + const roles = roleFactory.buildList(1, { + permissions: [Permission.FILESTORAGE_CREATE, Permission.FILESTORAGE_VIEW], + }); + const user = userFactory.build({ school, roles }); + + await em.persistAndFlush([user, school]); + em.clear(); + + currentUser = mapUserToCurrentUser(user); + }); + describe('with valid request params', () => { + it('should return 201 status', async () => { + const { createContentId, id, metadata } = setup(); + const result1 = { id, metadata }; + h5PEditorUc.saveH5pContentGetMetadata.mockResolvedValueOnce(result1); + const response = await api.createOrSave(createContentId); + expect(response.status).toEqual(201); + }); + }); + }); + describe('save h5p content', () => { + beforeEach(async () => { + await cleanupCollections(em); + const school = schoolFactory.build(); + const roles = roleFactory.buildList(1, { + permissions: [Permission.FILESTORAGE_CREATE, Permission.FILESTORAGE_VIEW], + }); + const user = userFactory.build({ school, roles }); + + await em.persistAndFlush([user, school]); + em.clear(); + + currentUser = mapUserToCurrentUser(user); + }); + describe('with valid request params', () => { + it('should return 201 status', async () => { + const { contentId, id, metadata } = setup(); + const result1 = { id, metadata }; + h5PEditorUc.saveH5pContentGetMetadata.mockResolvedValueOnce(result1); + const response = await api.createOrSave(contentId); + expect(response.status).toEqual(201); + }); + }); + describe('with bad request params', () => { + it('should return 500 status', async () => { + const { notExistingContentId } = setup(); + h5PEditorUc.saveH5pContentGetMetadata.mockRejectedValueOnce(new Error('Could not save H5P content')); + const response = await api.createOrSave(notExistingContentId); + expect(response.status).toEqual(500); + }); + }); + }); +}); diff --git a/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor.api.spec.ts b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor.api.spec.ts deleted file mode 100644 index f2e40310645..00000000000 --- a/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor.api.spec.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { EntityManager } from '@mikro-orm/core'; -import { HttpStatus, INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; -import { H5PEditorTestModule } from '@src/modules/h5p-editor/h5p-editor-test.module'; - -describe('H5PEditor Controller (api)', () => { - let app: INestApplication; - let em: EntityManager; - let testApiClient: TestApiClient; - - beforeAll(async () => { - const module = await Test.createTestingModule({ - imports: [H5PEditorTestModule], - }).compile(); - - app = module.createNestApplication(); - await app.init(); - em = app.get(EntityManager); - testApiClient = new TestApiClient(app, 'h5p-editor'); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('get player', () => { - describe('when user not exists', () => { - it('should respond with unauthorized exception', async () => { - const response = await testApiClient.get('dummyID/play'); - - expect(response.statusCode).toEqual(HttpStatus.UNAUTHORIZED); - expect(response.body).toEqual({ - type: 'UNAUTHORIZED', - title: 'Unauthorized', - message: 'Unauthorized', - code: 401, - }); - }); - }); - - describe('when user is allowed to view player', () => { - const createStudent = () => UserAndAccountTestFactory.buildStudent(); - - const setup = async () => { - const { studentAccount, studentUser } = createStudent(); - - await em.persistAndFlush([studentAccount, studentUser]); - em.clear(); - - const loggedInClient = await testApiClient.login(studentAccount); - - return { loggedInClient }; - }; - - it('should return the player', async () => { - const { loggedInClient } = await setup(); - - const response = await loggedInClient.get('dummyID/play'); - - expect(response.statusCode).toEqual(HttpStatus.OK); - expect(response.text).toContain('

H5P Player Dummy

'); - }); - }); - }); - - describe('get editor', () => { - describe('when user not exists', () => { - it('should respond with unauthorized exception', async () => { - const response = await testApiClient.get('dummyID/edit'); - - expect(response.statusCode).toEqual(HttpStatus.UNAUTHORIZED); - expect(response.body).toEqual({ - type: 'UNAUTHORIZED', - title: 'Unauthorized', - message: 'Unauthorized', - code: 401, - }); - }); - }); - - describe('when user is allowed to view editor', () => { - const createStudent = () => UserAndAccountTestFactory.buildStudent(); - - const setup = async () => { - const { studentAccount, studentUser } = createStudent(); - - await em.persistAndFlush([studentAccount, studentUser]); - em.clear(); - - const loggedInClient = await testApiClient.login(studentAccount); - - return { loggedInClient }; - }; - - it('should return the editor', async () => { - const { loggedInClient } = await setup(); - - const response = await loggedInClient.get('dummyID/edit'); - - expect(response.statusCode).toEqual(HttpStatus.OK); - expect(response.text).toContain('

H5P Editor Dummy

'); - }); - }); - }); -}); diff --git a/apps/server/src/modules/h5p-editor/controller/dto/ajax/get.params.ts b/apps/server/src/modules/h5p-editor/controller/dto/ajax/get.params.ts new file mode 100644 index 00000000000..50695c28b75 --- /dev/null +++ b/apps/server/src/modules/h5p-editor/controller/dto/ajax/get.params.ts @@ -0,0 +1,23 @@ +import { IsNotEmpty, IsOptional, IsString } from 'class-validator'; + +export class AjaxGetQueryParams { + @IsString() + @IsNotEmpty() + action!: string; + + @IsString() + @IsOptional() + machineName?: string; + + @IsString() + @IsOptional() + majorVersion?: string; + + @IsString() + @IsOptional() + minorVersion?: string; + + @IsString() + @IsOptional() + language?: string; +} diff --git a/apps/server/src/modules/h5p-editor/controller/dto/ajax/index.ts b/apps/server/src/modules/h5p-editor/controller/dto/ajax/index.ts new file mode 100644 index 00000000000..3410511d0cc --- /dev/null +++ b/apps/server/src/modules/h5p-editor/controller/dto/ajax/index.ts @@ -0,0 +1,3 @@ +export * from './get.params'; +export * from './post.body.params'; +export * from './post.params'; diff --git a/apps/server/src/modules/h5p-editor/controller/dto/ajax/post.body.params.ts b/apps/server/src/modules/h5p-editor/controller/dto/ajax/post.body.params.ts new file mode 100644 index 00000000000..73be80cbf45 --- /dev/null +++ b/apps/server/src/modules/h5p-editor/controller/dto/ajax/post.body.params.ts @@ -0,0 +1,72 @@ +import { BadRequestException, Injectable, PipeTransform, ValidationPipe } from '@nestjs/common'; +import { AnyFilesInterceptor } from '@nestjs/platform-express'; +import { ApiProperty } from '@nestjs/swagger'; +import { plainToClass } from 'class-transformer'; +import { IsArray, IsOptional, IsString, validate } from 'class-validator'; + +class LibrariesBodyParams { + @ApiProperty() + @IsArray() + @IsString({ each: true }) + libraries!: string[]; +} + +class ContentBodyParams { + @ApiProperty() + @IsString() + contentId!: string; + + @ApiProperty() + @IsString() + @IsOptional() + field!: string; // Todo: Reason +} + +class LibraryParametersBodyParams { + @ApiProperty() + @IsString() + libraryParameters!: string; +} + +export type AjaxPostBodyParams = LibrariesBodyParams | ContentBodyParams | LibraryParametersBodyParams | undefined; + +@Injectable() +export class AjaxPostBodyParamsTransformPipe implements PipeTransform { + async transform(value: AjaxPostBodyParams) { + if (value) { + let transformed: Exclude; + + if ('libraries' in value) { + transformed = plainToClass(LibrariesBodyParams, value); + } else if ('contentId' in value) { + transformed = plainToClass(ContentBodyParams, value); + } else if ('libraryParameters' in value) { + transformed = plainToClass(LibraryParametersBodyParams, value); + } else { + return undefined; // Todo Check this + } + + const validationResult = await validate(transformed); + if (validationResult.length > 0) { + const validationPipe = new ValidationPipe(); + const exceptionFactory = validationPipe.createExceptionFactory(); + throw exceptionFactory(validationResult); + } + + return transformed; + } + + return undefined; + } +} + +export const AjaxPostBodyParamsFilesInterceptor = AnyFilesInterceptor({ + limits: { files: 2 }, + fileFilter(_req, file, callback) { + if (file.fieldname === 'file' || file.fieldname === 'h5p') { + callback(null, true); + } else { + callback(new BadRequestException('File not allowed'), false); + } + }, +}); diff --git a/apps/server/src/modules/h5p-editor/controller/dto/ajax/post.params.ts b/apps/server/src/modules/h5p-editor/controller/dto/ajax/post.params.ts new file mode 100644 index 00000000000..b84dc984504 --- /dev/null +++ b/apps/server/src/modules/h5p-editor/controller/dto/ajax/post.params.ts @@ -0,0 +1,27 @@ +import { IsNotEmpty, IsOptional, IsString } from 'class-validator'; + +export class AjaxPostQueryParams { + @IsString() + @IsNotEmpty() + action!: string; + + @IsString() + @IsOptional() + machineName?: string; + + @IsString() + @IsOptional() + majorVersion?: string; + + @IsString() + @IsOptional() + minorVersion?: string; + + @IsString() + @IsOptional() + language?: string; + + @IsString() + @IsOptional() + id?: string; +} diff --git a/apps/server/src/modules/h5p-editor/controller/dto/content-file.url.params.ts b/apps/server/src/modules/h5p-editor/controller/dto/content-file.url.params.ts new file mode 100644 index 00000000000..f785ca9e77e --- /dev/null +++ b/apps/server/src/modules/h5p-editor/controller/dto/content-file.url.params.ts @@ -0,0 +1,14 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { IsNotEmpty, IsString } from 'class-validator'; + +export class ContentFileUrlParams { + @ApiProperty() + @IsString() + @IsNotEmpty() + id!: string; + + @ApiProperty() + @IsString() + @IsNotEmpty() + file!: string; +} diff --git a/apps/server/src/modules/h5p-editor/controller/dto/h5p-editor.params.ts b/apps/server/src/modules/h5p-editor/controller/dto/h5p-editor.params.ts new file mode 100644 index 00000000000..c049f563b81 --- /dev/null +++ b/apps/server/src/modules/h5p-editor/controller/dto/h5p-editor.params.ts @@ -0,0 +1,59 @@ +import { IContentMetadata } from '@lumieducation/h5p-server'; +import { ApiProperty } from '@nestjs/swagger'; +import { IsNotEmpty, IsObject, IsOptional, IsString, Matches } from 'class-validator'; + +export class GetH5PContentParams { + @ApiProperty() + @Matches('([a-z]+-[a-z]+)') + @IsString() + @IsOptional() + language?: string; + + @ApiProperty() + @Matches('([A-Z0-9a-z]+)') + @IsString() + @IsNotEmpty() + contentId!: string; +} + +export class PostH5PContentParams { + @ApiProperty() + @Matches('([A-Z0-9a-z]+)') + @IsString() + @IsNotEmpty() + contentId!: string; + + @ApiProperty() + @IsNotEmpty() + params!: unknown; + + @ApiProperty() + @IsNotEmpty() + metadata!: IContentMetadata; + + @ApiProperty() + @IsString() + @IsNotEmpty() + mainLibraryUbername!: string; +} + +export class PostH5PContentCreateParams { + @ApiProperty() + @IsNotEmpty() + @IsObject() + params!: { + // Todo + params: unknown; + metadata: IContentMetadata; + }; + + @ApiProperty() + @IsObject() + @IsOptional() + metadata!: IContentMetadata; + + @ApiProperty() + @IsString() + @IsNotEmpty() + library!: string; +} diff --git a/apps/server/src/modules/h5p-editor/controller/dto/index.ts b/apps/server/src/modules/h5p-editor/controller/dto/index.ts new file mode 100644 index 00000000000..8b5d966f881 --- /dev/null +++ b/apps/server/src/modules/h5p-editor/controller/dto/index.ts @@ -0,0 +1,4 @@ +export * from './ajax'; +export * from './content-file.url.params'; +export * from './h5p-editor.params'; +export * from './library-file.url.params'; diff --git a/apps/server/src/modules/h5p-editor/controller/dto/library-file.url.params.ts b/apps/server/src/modules/h5p-editor/controller/dto/library-file.url.params.ts new file mode 100644 index 00000000000..40d036b6e1f --- /dev/null +++ b/apps/server/src/modules/h5p-editor/controller/dto/library-file.url.params.ts @@ -0,0 +1,14 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { IsNotEmpty, IsString } from 'class-validator'; + +export class LibraryFileUrlParams { + @ApiProperty() + @IsString() + @IsNotEmpty() + ubername!: string; + + @ApiProperty() + @IsString() + @IsNotEmpty() + file!: string; +} diff --git a/apps/server/src/modules/h5p-editor/controller/h5p-editor.controller.ts b/apps/server/src/modules/h5p-editor/controller/h5p-editor.controller.ts index 9f2a15c1a1d..e17e00dd74e 100644 --- a/apps/server/src/modules/h5p-editor/controller/h5p-editor.controller.ts +++ b/apps/server/src/modules/h5p-editor/controller/h5p-editor.controller.ts @@ -1,7 +1,39 @@ -import { BadRequestException, Controller, ForbiddenException, Get, InternalServerErrorException } from '@nestjs/common'; +import { + BadRequestException, + Body, + Controller, + ForbiddenException, + Get, + HttpStatus, + InternalServerErrorException, + Param, + Post, + Query, + Req, + Res, + StreamableFile, + UploadedFiles, + UseInterceptors, +} from '@nestjs/common'; import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger'; import { ApiValidationError } from '@shared/common'; -import { Authenticate } from '@src/modules/authentication/decorator/auth.decorator'; +import { ICurrentUser } from '@src/modules/authentication'; +import { Authenticate, CurrentUser } from '@src/modules/authentication/decorator/auth.decorator'; +import { Request, Response } from 'express'; + +import { H5PEditorUc } from '../uc/h5p.uc'; + +import { + AjaxGetQueryParams, + AjaxPostBodyParams, + AjaxPostBodyParamsFilesInterceptor, + AjaxPostBodyParamsTransformPipe, + AjaxPostQueryParams, + ContentFileUrlParams, + GetH5PContentParams, + LibraryFileUrlParams, + PostH5PContentCreateParams, +} from './dto'; // Dummy html response so we can test i-frame integration const dummyResponse = (title: string) => ` @@ -24,15 +56,18 @@ const dummyResponse = (title: string) => ` @Authenticate('jwt') @Controller('h5p-editor') export class H5PEditorController { + constructor(private h5pEditorUc: H5PEditorUc) {} + @ApiOperation({ summary: 'Return dummy HTML for testing' }) @ApiResponse({ status: 400, type: ApiValidationError }) @ApiResponse({ status: 400, type: BadRequestException }) @ApiResponse({ status: 403, type: ForbiddenException }) @ApiResponse({ status: 500, type: InternalServerErrorException }) - @Get('/:contentId/play') - async getPlayer() { + @Get('/play/:contentId') + async getPlayer(@CurrentUser() currentUser: ICurrentUser, @Param() params: GetH5PContentParams) { + return this.h5pEditorUc.getH5pPlayer(currentUser, params.contentId); // Dummy Response - return Promise.resolve(dummyResponse('H5P Player Dummy')); + // return Promise.resolve(dummyResponse('H5P Player Dummy')); } @ApiOperation({ summary: 'Return dummy HTML for testing' }) @@ -53,4 +88,141 @@ export class H5PEditorController { // - ajax endpoint for h5p (e.g. GET/POST `/ajax/*`) // - static files from h5p-core (e.g. GET `/core/*`) // - static files for editor (e.g. GET `/editor/*`) + + @Get('libraries/:ubername/:file(*)') + async getLibraryFile(@Param() params: LibraryFileUrlParams, @Req() req: Request) { + const { data, contentType, contentLength } = await this.h5pEditorUc.getLibraryFile(params.ubername, params.file); + + req.on('close', () => data.destroy()); + + return new StreamableFile(data, { type: contentType, length: contentLength }); + } + + @Get('params/:id') + async getContentParameters(@Param('id') id: string, @CurrentUser() currentUser: ICurrentUser) { + const content = await this.h5pEditorUc.getContentParameters(id, currentUser); + + return content; + } + + @Get('content/:id/:file(*)') + async getContentFile( + @Param() params: ContentFileUrlParams, + @Req() req: Request, + @Res({ passthrough: true }) res: Response, + @CurrentUser() currentUser: ICurrentUser + ) { + const { data, contentType, contentLength, contentRange } = await this.h5pEditorUc.getContentFile( + params.id, + params.file, + req, + currentUser + ); + + if (contentRange) { + const contentRangeHeader = `bytes ${contentRange.start}-${contentRange.end}/${contentLength}`; + + res.set({ + 'Accept-Ranges': 'bytes', + 'Content-Range': contentRangeHeader, + }); + + res.status(HttpStatus.PARTIAL_CONTENT); + } else { + res.status(HttpStatus.OK); + } + + req.on('close', () => data.destroy()); + + return new StreamableFile(data, { type: contentType, length: contentLength }); + } + + @Get('temp-files/:file(*)') + async getTemporaryFile( + @CurrentUser() currentUser: ICurrentUser, + @Param('file') file: string, + @Req() req: Request, + @Res({ passthrough: true }) res: Response + ) { + const { data, contentType, contentLength, contentRange } = await this.h5pEditorUc.getTemporaryFile( + file, + req, + currentUser + ); + + if (contentRange) { + const contentRangeHeader = `bytes ${contentRange.start}-${contentRange.end}/${contentLength}`; + + res.set({ + 'Accept-Ranges': 'bytes', + 'Content-Range': contentRangeHeader, + }); + + res.status(HttpStatus.PARTIAL_CONTENT); + } else { + res.status(HttpStatus.OK); + } + + req.on('close', () => data.destroy()); + + return new StreamableFile(data, { type: contentType, length: contentLength }); + } + + @Get('ajax') + async getAjax(@Query() query: AjaxGetQueryParams, @CurrentUser() currentUser: ICurrentUser) { + const response = this.h5pEditorUc.getAjax(query, currentUser); + return response; + } + + @Post('ajax') + @UseInterceptors(AjaxPostBodyParamsFilesInterceptor) + async postAjax( + @Body(AjaxPostBodyParamsTransformPipe) body: AjaxPostBodyParams, + @Query() query: AjaxPostQueryParams, + @UploadedFiles() files: Express.Multer.File[], + @CurrentUser() currentUser: ICurrentUser + ) { + const result = await this.h5pEditorUc.postAjax(currentUser, query, body, files); + return result; + } + + @Post('/delete/:contentId') + async deleteH5pContent( + @Param() params: GetH5PContentParams, + @CurrentUser() currentUser: ICurrentUser + ): Promise { + const deleteSuccessfull = this.h5pEditorUc.deleteH5pContent(currentUser, params.contentId); + + return deleteSuccessfull; + } + + @Get('/:contentId') + async getH5PEditor(@Param() params: GetH5PContentParams, @CurrentUser() currentUser: ICurrentUser): Promise { + // TODO: Get user language + if (params.contentId === 'create') { + params.contentId = undefined as unknown as string; + } + const response = this.h5pEditorUc.getH5pEditor(currentUser, params.contentId, 'de'); + return response; + } + + @Post('/:contentId') + async createOrSaveH5pContent( + @Body() body: PostH5PContentCreateParams, + @Param() params: GetH5PContentParams, + @CurrentUser() currentUser: ICurrentUser + ) { + if (params.contentId === 'create') { + params.contentId = undefined as unknown as string; + } + const response = await this.h5pEditorUc.saveH5pContentGetMetadata( + params.contentId, + currentUser, + body.params.params, + body.params.metadata, + body.library + ); + + return response; + } } diff --git a/apps/server/src/modules/h5p-editor/h5p-editor-test.module.ts b/apps/server/src/modules/h5p-editor/h5p-editor-test.module.ts index bdd421258be..0f9607c95c3 100644 --- a/apps/server/src/modules/h5p-editor/h5p-editor-test.module.ts +++ b/apps/server/src/modules/h5p-editor/h5p-editor-test.module.ts @@ -1,3 +1,6 @@ +import os from 'node:os'; +import path from 'node:path'; + import { DynamicModule, Module } from '@nestjs/common'; import { Account, Role, School, SchoolYear, User } from '@shared/domain'; import { MongoMemoryDatabaseModule } from '@shared/infra/database'; @@ -5,10 +8,23 @@ import { MongoDatabaseModuleOptions } from '@shared/infra/database/mongo-memory- import { RabbitMQWrapperTestModule } from '@shared/infra/rabbitmq'; import { CoreModule } from '@src/core'; import { LoggerModule } from '@src/core/logger'; +import { AuthenticationApiModule } from '@src/modules/authentication/authentication-api.module'; import { AuthenticationModule } from '@src/modules/authentication/authentication.module'; import { AuthorizationModule } from '@src/modules/authorization'; -import { AuthenticationApiModule } from '../authentication/authentication-api.module'; + +import { ContentStorage } from './contentStorage/contentStorage'; +import { H5PEditorController } from './controller'; import { H5PEditorModule } from './h5p-editor.module'; +import { LibraryStorage } from './libraryStorage/libraryStorage'; +import { H5PAjaxEndpointService, H5PEditorService, H5PPlayerService } from './service'; +import { TemporaryFileStorage } from './temporary-file-storage/temporary-file-storage'; +import { H5PEditorUc } from './uc/h5p.uc'; + +const storages = [ + { provide: ContentStorage, useValue: new ContentStorage(path.join(os.tmpdir(), '/h5p_content')) }, + { provide: LibraryStorage, useValue: new LibraryStorage(path.join(os.tmpdir(), '/h5p_libraries')) }, + { provide: TemporaryFileStorage, useValue: new TemporaryFileStorage(path.join(os.tmpdir(), '/h5p_temporary')) }, +]; const imports = [ H5PEditorModule, @@ -20,8 +36,9 @@ const imports = [ LoggerModule, RabbitMQWrapperTestModule, ]; -const controllers = []; -const providers = []; +const controllers = [H5PEditorController]; +const providers = [H5PEditorUc, H5PPlayerService, H5PEditorService, H5PAjaxEndpointService, ...storages]; + @Module({ imports, controllers, diff --git a/apps/server/src/modules/h5p-editor/h5p-editor.module.ts b/apps/server/src/modules/h5p-editor/h5p-editor.module.ts index 638723787e5..6427af36e19 100644 --- a/apps/server/src/modules/h5p-editor/h5p-editor.module.ts +++ b/apps/server/src/modules/h5p-editor/h5p-editor.module.ts @@ -1,15 +1,28 @@ +import os from 'node:os'; +import path from 'node:path'; + import { Dictionary, IPrimaryKey } from '@mikro-orm/core'; import { MikroOrmModule, MikroOrmModuleSyncOptions } from '@mikro-orm/nestjs'; import { Module, NotFoundException } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { Account, Role, School, SchoolYear, System, User } from '@shared/domain'; +import { RabbitMQWrapperModule } from '@shared/infra/rabbitmq'; import { DB_PASSWORD, DB_URL, DB_USERNAME, createConfigModuleOptions } from '@src/config'; import { CoreModule } from '@src/core'; import { Logger } from '@src/core/logger'; +import { AuthenticationModule } from '@src/modules/authentication/authentication.module'; import { AuthorizationModule } from '@src/modules/authorization'; -import { AuthenticationModule } from '../authentication/authentication.module'; + import { H5PEditorController } from './controller/h5p-editor.controller'; import { config } from './h5p-editor.config'; +import { H5PAjaxEndpointService } from './service'; +import { H5PEditorService } from './service/h5p-editor.service'; +import { H5PPlayerService } from './service/h5p-player.service'; +import { H5PEditorUc } from './uc/h5p.uc'; + +import { ContentStorage } from './contentStorage/contentStorage'; +import { LibraryStorage } from './libraryStorage/libraryStorage'; +import { TemporaryFileStorage } from './temporary-file-storage/temporary-file-storage'; const defaultMikroOrmOptions: MikroOrmModuleSyncOptions = { findOneOrFailHandler: (entityName: string, where: Dictionary | IPrimaryKey) => @@ -17,10 +30,17 @@ const defaultMikroOrmOptions: MikroOrmModuleSyncOptions = { new NotFoundException(`The requested ${entityName}: ${where} has not been found.`), }; +const storages = [ + { provide: ContentStorage, useValue: new ContentStorage(path.join(os.tmpdir(), '/h5p_content')) }, + { provide: LibraryStorage, useValue: new LibraryStorage(path.join(os.tmpdir(), '/h5p_libraries')) }, + { provide: TemporaryFileStorage, useValue: new TemporaryFileStorage(path.join(os.tmpdir(), '/h5p_temporary')) }, +]; + const imports = [ AuthenticationModule, AuthorizationModule, CoreModule, + RabbitMQWrapperModule, MikroOrmModule.forRoot({ ...defaultMikroOrmOptions, type: 'mongo', @@ -37,7 +57,7 @@ const imports = [ const controllers = [H5PEditorController]; -const providers = [Logger]; +const providers = [Logger, H5PEditorUc, H5PEditorService, H5PPlayerService, H5PAjaxEndpointService, ...storages]; @Module({ imports, diff --git a/apps/server/src/modules/h5p-editor/service/h5p-ajax-endpoint.service.ts b/apps/server/src/modules/h5p-editor/service/h5p-ajax-endpoint.service.ts new file mode 100644 index 00000000000..07dd9f83222 --- /dev/null +++ b/apps/server/src/modules/h5p-editor/service/h5p-ajax-endpoint.service.ts @@ -0,0 +1,11 @@ +import { H5PAjaxEndpoint, H5PEditor } from '@lumieducation/h5p-server'; + +export const H5PAjaxEndpointService = { + provide: H5PAjaxEndpoint, + inject: [H5PEditor], + useFactory: (h5pEditor: H5PEditor) => { + const h5pAjaxEndpoint = new H5PAjaxEndpoint(h5pEditor); + + return h5pAjaxEndpoint; + }, +}; diff --git a/apps/server/src/modules/h5p-editor/service/h5p-editor.service.ts b/apps/server/src/modules/h5p-editor/service/h5p-editor.service.ts new file mode 100644 index 00000000000..e5b29475deb --- /dev/null +++ b/apps/server/src/modules/h5p-editor/service/h5p-editor.service.ts @@ -0,0 +1,33 @@ +import { H5PConfig, H5PEditor, UrlGenerator, cacheImplementations } from '@lumieducation/h5p-server'; + +import { ContentStorage } from '../contentStorage/contentStorage'; +import { LibraryStorage } from '../libraryStorage/libraryStorage'; +import { TemporaryFileStorage } from '../temporary-file-storage/temporary-file-storage'; + +export const H5PEditorService = { + provide: H5PEditor, + inject: [ContentStorage, LibraryStorage, TemporaryFileStorage], + useFactory(contentStorage: ContentStorage, libraryStorage: LibraryStorage, temporaryStorage: TemporaryFileStorage) { + const cache = new cacheImplementations.CachedKeyValueStorage('kvcache'); + + const config: H5PConfig = new H5PConfig(undefined, { + baseUrl: '/api/v3/h5p-editor', + contentUserStateSaveInterval: false, + }); + + const urlGenerator = new UrlGenerator(config); + + const h5pEditor = new H5PEditor( + cache, + config, + libraryStorage, + contentStorage, + temporaryStorage, + undefined, + urlGenerator, + undefined + ); + + return h5pEditor; + }, +}; diff --git a/apps/server/src/modules/h5p-editor/service/h5p-player.service.ts b/apps/server/src/modules/h5p-editor/service/h5p-player.service.ts new file mode 100644 index 00000000000..4be3af5848b --- /dev/null +++ b/apps/server/src/modules/h5p-editor/service/h5p-player.service.ts @@ -0,0 +1,30 @@ +import { H5PConfig, H5PPlayer, UrlGenerator } from '@lumieducation/h5p-server'; + +import { ContentStorage } from '../contentStorage/contentStorage'; +import { LibraryStorage } from '../libraryStorage/libraryStorage'; + +export const H5PPlayerService = { + provide: H5PPlayer, + inject: [ContentStorage, LibraryStorage], + useFactory: (contentStorage: ContentStorage, libraryStorage: LibraryStorage) => { + const config: H5PConfig = new H5PConfig(undefined, { + baseUrl: '/api/v3/h5p-editor', + contentUserStateSaveInterval: false, + }); + + const urlGenerator = new UrlGenerator(config); + + const h5pPlayer = new H5PPlayer( + libraryStorage, + contentStorage, + config, + undefined, + urlGenerator, + undefined, + undefined, + undefined + ); + + return h5pPlayer; + }, +}; diff --git a/apps/server/src/modules/h5p-editor/service/index.ts b/apps/server/src/modules/h5p-editor/service/index.ts new file mode 100644 index 00000000000..3db25c02872 --- /dev/null +++ b/apps/server/src/modules/h5p-editor/service/index.ts @@ -0,0 +1,3 @@ +export * from './h5p-editor.service'; +export * from './h5p-player.service'; +export * from './h5p-ajax-endpoint.service'; diff --git a/apps/server/src/modules/h5p-editor/uc/h5p-ajax.uc.spec.ts b/apps/server/src/modules/h5p-editor/uc/h5p-ajax.uc.spec.ts new file mode 100644 index 00000000000..9147174634a --- /dev/null +++ b/apps/server/src/modules/h5p-editor/uc/h5p-ajax.uc.spec.ts @@ -0,0 +1,204 @@ +import { DeepMocked, createMock } from '@golevelup/ts-jest'; +import { H5PAjaxEndpoint, H5pError } from '@lumieducation/h5p-server'; +import { HttpException, InternalServerErrorException } from '@nestjs/common'; +import { Test, TestingModule } from '@nestjs/testing'; +import { setupEntities } from '@shared/testing'; +import { H5PEditorTestModule } from '../h5p-editor-test.module'; +import { H5PEditorUc } from './h5p.uc'; + +describe('H5P Ajax', () => { + let module: TestingModule; + let uc: H5PEditorUc; + let ajaxEndpoint: DeepMocked; + + beforeAll(async () => { + module = await Test.createTestingModule({ + imports: [H5PEditorTestModule], + }) + .overrideProvider(H5PAjaxEndpoint) + .useValue(createMock()) + .compile(); + + uc = module.get(H5PEditorUc); + ajaxEndpoint = module.get(H5PAjaxEndpoint); + await setupEntities(); + }); + + afterEach(() => { + jest.resetAllMocks(); + }); + + afterAll(async () => { + await module.close(); + }); + + describe('when calling GET', () => { + const userMock = { userId: 'dummyId', roles: [], schoolId: 'dummySchool', accountId: 'dummyAccountId' }; + + it('should call H5PAjaxEndpoint.getAjax and return the result', async () => { + const dummyResponse = { + apiVersion: { major: 1, minor: 1 }, + details: [], + libraries: [], + outdated: false, + recentlyUsed: [], + user: 'DummyUser', + }; + + ajaxEndpoint.getAjax.mockResolvedValueOnce(dummyResponse); + + const result = await uc.getAjax({ action: 'content-type-cache', language: 'de' }, userMock); + + expect(result).toBe(dummyResponse); + expect(ajaxEndpoint.getAjax).toHaveBeenCalledWith( + 'content-type-cache', + undefined, // MachineName + undefined, // MajorVersion + undefined, // MinorVersion + 'de', + expect.objectContaining({ id: 'dummyId' }) + ); + }); + + it('should convert any H5P-Errors into HttpExceptions', async () => { + ajaxEndpoint.getAjax.mockRejectedValueOnce(new H5pError('dummy-error', { error: 'Dummy Error' }, 400)); + + const result = uc.getAjax({ action: 'content-type-cache', language: 'de' }, userMock); + + await expect(result).rejects.toThrowError(new HttpException('dummy-error (error: Dummy Error)', 400)); + }); + + it('should convert any non-H5P-Errors into InternalServerErrorException', async () => { + ajaxEndpoint.getAjax.mockRejectedValueOnce(new Error('Dummy Error')); + + const result = uc.getAjax({ action: 'content-type-cache', language: 'de' }, userMock); + + await expect(result).rejects.toThrowError(InternalServerErrorException); + }); + }); + + describe('when calling POST', () => { + const userMock = { userId: 'dummyId', roles: [], schoolId: 'dummySchool', accountId: 'dummyAccountId' }; + + it('should call H5PAjaxEndpoint.postAjax and return the result', async () => { + const dummyResponse = [ + { + majorVersion: 1, + minorVersion: 2, + metadataSettings: {}, + name: 'Dummy Library', + restricted: false, + runnable: true, + title: 'Dummy Library', + tutorialUrl: '', + uberName: 'dummyLibrary-1.1', + }, + ]; + + ajaxEndpoint.postAjax.mockResolvedValueOnce(dummyResponse); + + const result = await uc.postAjax( + userMock, + { action: 'libraries' }, + { contentId: 'id', field: 'field', libraries: ['dummyLibrary-1.0'], libraryParameters: '' } + ); + + expect(result).toBe(dummyResponse); + expect(ajaxEndpoint.postAjax).toHaveBeenCalledWith( + 'libraries', + { contentId: 'id', field: 'field', libraries: ['dummyLibrary-1.0'], libraryParameters: '' }, + undefined, + expect.objectContaining({ id: 'dummyId' }), + undefined, + undefined, + undefined, + undefined, + undefined + ); + }); + + it('should call H5PAjaxEndpoint.postAjax with files', async () => { + const dummyResponse = [ + { + majorVersion: 1, + minorVersion: 2, + metadataSettings: {}, + name: 'Dummy Library', + restricted: false, + runnable: true, + title: 'Dummy Library', + tutorialUrl: '', + uberName: 'dummyLibrary-1.1', + }, + ]; + + ajaxEndpoint.postAjax.mockResolvedValueOnce(dummyResponse); + + const result = await uc.postAjax( + userMock, + { action: 'libraries' }, + { contentId: 'id', field: 'field', libraries: ['dummyLibrary-1.0'], libraryParameters: '' }, + [ + { + fieldname: 'file', + buffer: Buffer.from(''), + originalname: 'OriginalFile.jpg', + size: 0, + mimetype: 'image/jpg', + } as Express.Multer.File, + { + fieldname: 'h5p', + buffer: Buffer.from(''), + originalname: 'OriginalFile.jpg', + size: 0, + mimetype: 'image/jpg', + } as Express.Multer.File, + ] + ); + + const bufferTest = { + data: expect.any(Buffer), + mimetype: 'image/jpg', + name: 'OriginalFile.jpg', + size: 0, + }; + + expect(result).toBe(dummyResponse); + expect(ajaxEndpoint.postAjax).toHaveBeenCalledWith( + 'libraries', + { contentId: 'id', field: 'field', libraries: ['dummyLibrary-1.0'], libraryParameters: '' }, + undefined, + expect.objectContaining({ id: 'dummyId' }), + bufferTest, + undefined, + undefined, + bufferTest, + undefined + ); + }); + + it('should convert any H5P-Errors into HttpExceptions', async () => { + ajaxEndpoint.postAjax.mockRejectedValueOnce(new H5pError('dummy-error', { error: 'Dummy Error' }, 400)); + + const result = uc.postAjax( + userMock, + { action: 'libraries' }, + { contentId: 'id', field: 'field', libraries: ['dummyLibrary-1.0'], libraryParameters: '' } + ); + + await expect(result).rejects.toThrowError(new HttpException('dummy-error (error: Dummy Error)', 400)); + }); + + it('should convert any non-H5P-Errors into InternalServerErrorException', async () => { + ajaxEndpoint.postAjax.mockRejectedValueOnce(new Error('Dummy Error')); + + const result = uc.postAjax( + userMock, + { action: 'libraries' }, + { contentId: 'id', field: 'field', libraries: ['dummyLibrary-1.0'], libraryParameters: '' } + ); + + await expect(result).rejects.toThrowError(InternalServerErrorException); + }); + }); +}); diff --git a/apps/server/src/modules/h5p-editor/uc/h5p-delete.uc.spec.ts b/apps/server/src/modules/h5p-editor/uc/h5p-delete.uc.spec.ts new file mode 100644 index 00000000000..79ac99e91e3 --- /dev/null +++ b/apps/server/src/modules/h5p-editor/uc/h5p-delete.uc.spec.ts @@ -0,0 +1,74 @@ +import { DeepMocked, createMock } from '@golevelup/ts-jest'; +import { Test, TestingModule } from '@nestjs/testing'; +import { setupEntities } from '@shared/testing'; +import { ICurrentUser } from '@src/modules/authentication'; +import { H5PEditor } from '@lumieducation/h5p-server'; +import { H5PEditorTestModule } from '../h5p-editor-test.module'; +import { H5PEditorUc } from './h5p.uc'; + +const setup = () => { + const contentId = '123456789'; + const notExistingContentId = '999999999'; + const currentUser: ICurrentUser = { + userId: '123', + roles: [], + schoolId: '', + accountId: '', + }; + const error = new Error('Could not delete H5P content'); + const errorThrown = new Error('Error: Could not delete H5P content'); + + return { + contentId, + notExistingContentId, + currentUser, + error, + errorThrown, + }; +}; + +describe('save or create H5P content', () => { + let module: TestingModule; + let uc: H5PEditorUc; + let h5pEditor: DeepMocked; + + beforeAll(async () => { + module = await Test.createTestingModule({ + imports: [H5PEditorTestModule], + }) + .overrideProvider(H5PEditor) + .useValue(createMock()) + .compile(); + + uc = module.get(H5PEditorUc); + h5pEditor = module.get(H5PEditor); + await setupEntities(); + }); + + afterEach(() => { + jest.resetAllMocks(); + }); + + afterAll(async () => { + await module.close(); + }); + + describe('when contentId is given', () => { + it('should render h5p editor', async () => { + const { contentId, currentUser } = setup(); + // h5pEditor.saveOrUpdateContentReturnMetaData.mockResolvedValue(); + const result = await uc.deleteH5pContent(currentUser, contentId); + + expect(result).toEqual(true); + }); + }); + + describe('when contentId does not exist', () => { + it('should throw an error ', async () => { + const { notExistingContentId, currentUser, error, errorThrown } = setup(); + h5pEditor.deleteContent.mockRejectedValueOnce(error); + + await expect(uc.deleteH5pContent(currentUser, notExistingContentId)).rejects.toThrowError(errorThrown); + }); + }); +}); diff --git a/apps/server/src/modules/h5p-editor/uc/h5p-files.uc.spec.ts b/apps/server/src/modules/h5p-editor/uc/h5p-files.uc.spec.ts new file mode 100644 index 00000000000..0e4c630d3cd --- /dev/null +++ b/apps/server/src/modules/h5p-editor/uc/h5p-files.uc.spec.ts @@ -0,0 +1,331 @@ +import { DeepMocked, createMock } from '@golevelup/ts-jest'; +import { ContentMetadata } from '@lumieducation/h5p-server/build/src/ContentMetadata'; +import { Test, TestingModule } from '@nestjs/testing'; +import { setupEntities } from '@shared/testing'; +import { Request } from 'express'; +import { Readable } from 'stream'; + +import { H5PEditorTestModule } from '../h5p-editor-test.module'; +import { H5PEditorUc } from './h5p.uc'; + +import { ContentStorage } from '../contentStorage/contentStorage'; +import { LibraryStorage } from '../libraryStorage/libraryStorage'; +import { TemporaryFileStorage } from '../temporary-file-storage/temporary-file-storage'; + +describe('H5P Files', () => { + let module: TestingModule; + let uc: H5PEditorUc; + let contentStorage: DeepMocked; + let libraryStorage: DeepMocked; + let temporaryStorage: DeepMocked; + + beforeAll(async () => { + module = await Test.createTestingModule({ + imports: [H5PEditorTestModule], + }) + .overrideProvider(ContentStorage) + .useValue(createMock()) + .overrideProvider(LibraryStorage) + .useValue(createMock()) + .overrideProvider(TemporaryFileStorage) + .useValue(createMock()) + .compile(); + + uc = module.get(H5PEditorUc); + contentStorage = module.get(ContentStorage); + libraryStorage = module.get(LibraryStorage); + temporaryStorage = module.get(TemporaryFileStorage); + await setupEntities(); + }); + + afterEach(() => { + jest.resetAllMocks(); + }); + + afterAll(async () => { + await module.close(); + }); + + describe('when getting content parameters', () => { + const userMock = { userId: 'dummyId', roles: [], schoolId: 'dummySchool', accountId: 'dummyAccountId' }; + + it('should call ContentStorage and return the result', async () => { + const dummyMetadata = new ContentMetadata(); + const dummyParams = { name: 'Dummy' }; + + contentStorage.getMetadata.mockResolvedValueOnce(dummyMetadata); + contentStorage.getParameters.mockResolvedValueOnce(dummyParams); + + const result = await uc.getContentParameters('dummylib-1.0', userMock); + + expect(result).toEqual({ + h5p: dummyMetadata, + params: { metadata: dummyMetadata, params: dummyParams }, + }); + }); + + it('should throw an error if the content does not exist', async () => { + contentStorage.getMetadata.mockRejectedValueOnce(new Error('Could not get Metadata')); + contentStorage.getParameters.mockRejectedValueOnce(new Error('Could not get Parameters')); + + const result = uc.getContentParameters('dummylib-1.0', userMock); + + await expect(result).rejects.toThrow(); + }); + }); + + describe('when getting content file', () => { + const setup = ( + contentId: string, + filename: string, + content: string, + rangeCallbackReturnValue?: { start: number; end: number }[] | -1 | -2 + ) => { + const fileDate = new Date(); + + const readableContent = Readable.from(content); + const contentLength = content.length; + + let contentRange: { start: number; end: number } | undefined; + if (rangeCallbackReturnValue && rangeCallbackReturnValue !== -1 && rangeCallbackReturnValue !== -2) { + contentRange = rangeCallbackReturnValue[0]; + } + + contentStorage.getFileStats.mockResolvedValueOnce({ birthtime: fileDate, size: contentLength }); + contentStorage.getFileStream.mockResolvedValueOnce(readableContent); + + const requestMock = { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + range: (size: number) => rangeCallbackReturnValue, + } as Request; + + const userMock = { userId: 'dummyId', roles: [], schoolId: 'dummySchool', accountId: 'dummyAccountId' }; + + return { contentId, filename, requestMock, contentRange, contentLength, readableContent, userMock }; + }; + + it('should call ContentStorage and return the result', async () => { + const { contentId, filename, requestMock, contentLength, contentRange, readableContent, userMock } = setup( + 'DummyId', + 'dummy-file.jpg', + 'File Content' + ); + + const result = await uc.getContentFile(contentId, filename, requestMock, userMock); + + expect(result).toStrictEqual({ + data: readableContent, + contentType: 'image/jpeg', + contentLength, + contentRange, + }); + + expect(contentStorage.getFileStats).toHaveBeenCalledWith( + contentId, + filename, + expect.objectContaining({ id: 'dummyId' }) + ); + expect(contentStorage.getFileStream).toHaveBeenCalledWith( + contentId, + filename, + expect.objectContaining({ id: 'dummyId' }), + contentRange?.start, + contentRange?.end + ); + }); + + it('should accept ranges', async () => { + const content = 'File Content'; + + const { contentId, filename, requestMock, contentLength, contentRange, readableContent, userMock } = setup( + 'DummyId', + 'dummy-file.jpg', + content, + [{ start: 0, end: content.length }] + ); + + const result = await uc.getContentFile(contentId, filename, requestMock, userMock); + + expect(result).toStrictEqual({ + data: readableContent, + contentType: 'image/jpeg', + contentLength, + contentRange, + }); + + expect(contentStorage.getFileStats).toHaveBeenCalledWith( + contentId, + filename, + expect.objectContaining({ id: 'dummyId' }) + ); + expect(contentStorage.getFileStream).toHaveBeenCalledWith( + contentId, + filename, + expect.objectContaining({ id: 'dummyId' }), + contentRange?.start, + contentRange?.end + ); + }); + + it('should fail on invalid ranges', async () => { + const { contentId, filename, requestMock, userMock } = setup('DummyId', 'dummy-file.jpg', 'File Content', -2); + const result = uc.getContentFile(contentId, filename, requestMock, userMock); + await expect(result).rejects.toThrow(); + }); + + it('should fail on unsatisfiable ranges', async () => { + const { contentId, filename, requestMock, userMock } = setup('DummyId', 'dummy-file.jpg', 'File Content', -1); + const result = uc.getContentFile(contentId, filename, requestMock, userMock); + await expect(result).rejects.toThrow(); + }); + + it('should fail on multipart ranges', async () => { + const { contentId, filename, requestMock, userMock } = setup('DummyId', 'dummy-file.jpg', 'File Content', [ + { start: 0, end: 5 }, + { start: 8, end: 12 }, + ]); + const result = uc.getContentFile(contentId, filename, requestMock, userMock); + await expect(result).rejects.toThrow(); + }); + }); + + describe('when getting library file', () => { + const setup = (ubername: string, filename: string, content: string) => { + const fileDate = new Date(); + + const readableContent = Readable.from(content); + const contentLength = content.length; + libraryStorage.getFileStats.mockResolvedValueOnce({ birthtime: fileDate, size: contentLength }); + libraryStorage.getFileStream.mockResolvedValueOnce(readableContent); + + return { ubername, filename, contentLength, readableContent }; + }; + + it('should call LibraryStorage and return the result', async () => { + const { ubername, filename, contentLength, readableContent } = setup( + 'H5P.Example-1.0', + 'dummy-file.jpg', + 'File Content' + ); + + const result = await uc.getLibraryFile(ubername, filename); + + expect(result).toStrictEqual({ + data: readableContent, + contentType: 'image/jpeg', + contentLength, + }); + + expect(libraryStorage.getFileStats).toHaveBeenCalledWith( + { machineName: 'H5P.Example', majorVersion: 1, minorVersion: 0 }, + 'dummy-file.jpg' + ); + expect(libraryStorage.getFileStream).toHaveBeenCalledWith( + { machineName: 'H5P.Example', majorVersion: 1, minorVersion: 0 }, + 'dummy-file.jpg' + ); + }); + }); + + describe('when getting temporary file', () => { + const setup = ( + filename: string, + content: string, + rangeCallbackReturnValue?: { start: number; end: number }[] | -1 | -2 + ) => { + const fileDate = new Date(); + + const readableContent = Readable.from(content); + const contentLength = content.length; + + let contentRange: { start: number; end: number } | undefined; + if (rangeCallbackReturnValue && rangeCallbackReturnValue !== -1 && rangeCallbackReturnValue !== -2) { + contentRange = rangeCallbackReturnValue[0]; + } + + temporaryStorage.getFileStats.mockResolvedValueOnce({ birthtime: fileDate, size: contentLength }); + temporaryStorage.getFileStream.mockResolvedValueOnce(readableContent); + + const requestMock = { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + range: (size: number) => rangeCallbackReturnValue, + } as Request; + + const userMock = { userId: 'dummyId', roles: [], schoolId: 'dummySchool', accountId: 'dummyAccountId' }; + + return { filename, requestMock, contentRange, contentLength, readableContent, userMock }; + }; + + it('should call ContentStorage and return the result', async () => { + const { filename, requestMock, contentLength, contentRange, readableContent, userMock } = setup( + 'dummy-file.jpg', + 'File Content' + ); + + const result = await uc.getTemporaryFile(filename, requestMock, userMock); + + expect(result).toStrictEqual({ + data: readableContent, + contentType: 'image/jpeg', + contentLength, + contentRange, + }); + + expect(temporaryStorage.getFileStats).toHaveBeenCalledWith(filename, expect.objectContaining({ id: 'dummyId' })); + expect(temporaryStorage.getFileStream).toHaveBeenCalledWith( + filename, + expect.objectContaining({ id: 'dummyId' }), + contentRange?.start, + contentRange?.end + ); + }); + + it('should accept ranges', async () => { + const content = 'File Content'; + + const { filename, requestMock, contentLength, contentRange, readableContent, userMock } = setup( + 'dummy-file.jpg', + content, + [{ start: 0, end: content.length }] + ); + + const result = await uc.getTemporaryFile(filename, requestMock, userMock); + + expect(result).toStrictEqual({ + data: readableContent, + contentType: 'image/jpeg', + contentLength, + contentRange, + }); + + expect(temporaryStorage.getFileStats).toHaveBeenCalledWith(filename, expect.objectContaining({ id: 'dummyId' })); + expect(temporaryStorage.getFileStream).toHaveBeenCalledWith( + filename, + expect.objectContaining({ id: 'dummyId' }), + contentRange?.start, + contentRange?.end + ); + }); + + it('should fail on invalid ranges', async () => { + const { filename, requestMock, userMock } = setup('dummy-file.jpg', 'File Content', -2); + const result = uc.getTemporaryFile(filename, requestMock, userMock); + await expect(result).rejects.toThrow(); + }); + + it('should fail on unsatisfiable ranges', async () => { + const { filename, requestMock, userMock } = setup('dummy-file.jpg', 'File Content', -2); + const result = uc.getTemporaryFile(filename, requestMock, userMock); + await expect(result).rejects.toThrow(); + }); + + it('should fail on multipart ranges', async () => { + const { filename, requestMock, userMock } = setup('dummy-file.jpg', 'File Content', [ + { start: 0, end: 5 }, + { start: 8, end: 12 }, + ]); + const result = uc.getTemporaryFile(filename, requestMock, userMock); + await expect(result).rejects.toThrow(); + }); + }); +}); diff --git a/apps/server/src/modules/h5p-editor/uc/h5p-get-editor.uc.spec.ts b/apps/server/src/modules/h5p-editor/uc/h5p-get-editor.uc.spec.ts new file mode 100644 index 00000000000..a13df197e41 --- /dev/null +++ b/apps/server/src/modules/h5p-editor/uc/h5p-get-editor.uc.spec.ts @@ -0,0 +1,79 @@ +import { DeepMocked, createMock } from '@golevelup/ts-jest'; +import { Test, TestingModule } from '@nestjs/testing'; +import { setupEntities } from '@shared/testing'; +import { ICurrentUser } from '@src/modules/authentication'; +import { H5PEditor } from '@lumieducation/h5p-server'; +import { H5PEditorTestModule } from '../h5p-editor-test.module'; +import { H5PEditorUc } from './h5p.uc'; + +const setup = () => { + const contentId = '123456789'; + const contentIdCreate = 'create'; + const language = 'de'; + const currentUser: ICurrentUser = { + userId: '123', + roles: [], + schoolId: '', + accountId: '', + }; + const iFrame = 'iFrame'; + + return { contentId, contentIdCreate, language, currentUser, iFrame }; +}; + +describe('get H5P editor', () => { + let module: TestingModule; + let uc: H5PEditorUc; + let h5pEditor: DeepMocked; + + beforeAll(async () => { + module = await Test.createTestingModule({ + imports: [H5PEditorTestModule], + }) + .overrideProvider(H5PEditor) + .useValue(createMock()) + .compile(); + + uc = module.get(H5PEditorUc); + h5pEditor = module.get(H5PEditor); + await setupEntities(); + }); + + afterEach(() => { + jest.resetAllMocks(); + }); + + afterAll(async () => { + await module.close(); + }); + + describe('when value of contentId is create', () => { + it('should render new h5p editor', async () => { + const { contentIdCreate, language, currentUser, iFrame } = setup(); + h5pEditor.render.mockResolvedValueOnce(iFrame); + const result = await uc.getH5pEditor(currentUser, contentIdCreate, language); + + expect(result).toEqual('iFrame'); + }); + }); + + describe('when contentId is given', () => { + it('should render h5p editor', async () => { + const { contentId, language, currentUser, iFrame } = setup(); + h5pEditor.render.mockResolvedValueOnce(iFrame); + const result = await uc.getH5pEditor(currentUser, contentId, language); + + expect(result).toEqual('iFrame'); + }); + }); + + describe('when contentId does not exist', () => { + it('should throw an error ', async () => { + const { contentId, language, currentUser } = setup(); + h5pEditor.render.mockRejectedValueOnce(new Error('Could not get H5P editor')); + const result = uc.getH5pEditor(currentUser, contentId, language); + + await expect(result).rejects.toThrow(); + }); + }); +}); diff --git a/apps/server/src/modules/h5p-editor/uc/h5p-get-player.uc.spec.ts b/apps/server/src/modules/h5p-editor/uc/h5p-get-player.uc.spec.ts new file mode 100644 index 00000000000..f307f9afc37 --- /dev/null +++ b/apps/server/src/modules/h5p-editor/uc/h5p-get-player.uc.spec.ts @@ -0,0 +1,68 @@ +import { DeepMocked, createMock } from '@golevelup/ts-jest'; +import { Test, TestingModule } from '@nestjs/testing'; +import { setupEntities } from '@shared/testing'; +import { ICurrentUser } from '@src/modules/authentication'; +import { H5PPlayer } from '@lumieducation/h5p-server'; +import { H5PEditorTestModule } from '../h5p-editor-test.module'; +import { H5PEditorUc } from './h5p.uc'; + +const setup = () => { + const contentId = '123456789'; + const notExistingContentId = '0000'; + const currentUser: ICurrentUser = { + userId: '123', + roles: [], + schoolId: '', + accountId: '', + }; + const htmlString = 'htmlString'; + + return { contentId, notExistingContentId, currentUser, htmlString }; +}; + +describe('get H5P player', () => { + let module: TestingModule; + let uc: H5PEditorUc; + let h5pPlayer: DeepMocked; + + beforeAll(async () => { + module = await Test.createTestingModule({ + imports: [H5PEditorTestModule], + }) + .overrideProvider(H5PPlayer) + .useValue(createMock()) + .compile(); + + uc = module.get(H5PEditorUc); + h5pPlayer = module.get(H5PPlayer); + await setupEntities(); + }); + + afterEach(() => { + jest.resetAllMocks(); + }); + + afterAll(async () => { + await module.close(); + }); + + describe('when contentId is given', () => { + it('should render h5p player', async () => { + const { contentId, currentUser, htmlString } = setup(); + h5pPlayer.render.mockResolvedValueOnce(htmlString); + const result = await uc.getH5pPlayer(currentUser, contentId); + + expect(result).toEqual('htmlString'); + }); + }); + + describe('when contentId does not exist', () => { + it('should throw an error', async () => { + const { notExistingContentId, currentUser } = setup(); + h5pPlayer.render.mockRejectedValueOnce(new Error('Could not get H5P player')); + const result = uc.getH5pPlayer(currentUser, notExistingContentId); + + await expect(result).rejects.toThrow(); + }); + }); +}); diff --git a/apps/server/src/modules/h5p-editor/uc/h5p-save-create.uc.spec.ts b/apps/server/src/modules/h5p-editor/uc/h5p-save-create.uc.spec.ts new file mode 100644 index 00000000000..248b5f93d33 --- /dev/null +++ b/apps/server/src/modules/h5p-editor/uc/h5p-save-create.uc.spec.ts @@ -0,0 +1,109 @@ +import { DeepMocked, createMock } from '@golevelup/ts-jest'; +import { Test, TestingModule } from '@nestjs/testing'; +import { setupEntities } from '@shared/testing'; +import { ICurrentUser } from '@src/modules/authentication'; +import { H5PEditor, IContentMetadata } from '@lumieducation/h5p-server'; +import { H5PEditorTestModule } from '../h5p-editor-test.module'; +import { H5PEditorUc } from './h5p.uc'; + +const setup = () => { + const contentId = '123456789'; + const notExistingContentId = '999999999'; + const id = '0000000'; + const metadata: IContentMetadata = { + embedTypes: [], + language: 'de', + mainLibrary: 'mainLib', + preloadedDependencies: [], + defaultLanguage: '', + license: '', + title: '123', + }; + const params = {}; + const contentIdUndefined = undefined as unknown as string; + const mainLibraryUbername = 'mainLib'; + const currentUser: ICurrentUser = { + userId: '123', + roles: [], + schoolId: '', + accountId: '', + }; + const error = new Error('Could not save H5P content'); + + return { + contentId, + contentIdUndefined, + notExistingContentId, + currentUser, + params, + metadata, + mainLibraryUbername, + id, + error, + }; +}; + +describe('save or create H5P content', () => { + let module: TestingModule; + let uc: H5PEditorUc; + let h5pEditor: DeepMocked; + + beforeAll(async () => { + module = await Test.createTestingModule({ + imports: [H5PEditorTestModule], + }) + .overrideProvider(H5PEditor) + .useValue(createMock()) + .compile(); + + uc = module.get(H5PEditorUc); + h5pEditor = module.get(H5PEditor); + await setupEntities(); + }); + + afterEach(() => { + jest.resetAllMocks(); + }); + + afterAll(async () => { + await module.close(); + }); + + describe('when value of contentId is create', () => { + it('should create new h5p content', async () => { + const { contentIdUndefined, metadata, mainLibraryUbername, params, currentUser, id } = setup(); + const result1 = { id, metadata }; + h5pEditor.saveOrUpdateContentReturnMetaData.mockResolvedValueOnce(result1); + const result = await uc.saveH5pContentGetMetadata( + contentIdUndefined, + currentUser, + params, + metadata, + mainLibraryUbername + ); + + expect(result).toEqual(result1); + }); + }); + + describe('when contentId is given', () => { + it('should render h5p editor', async () => { + const { contentId, metadata, mainLibraryUbername, params, currentUser, id } = setup(); + const result1 = { id, metadata }; + h5pEditor.saveOrUpdateContentReturnMetaData.mockResolvedValueOnce(result1); + const result = await uc.saveH5pContentGetMetadata(contentId, currentUser, params, metadata, mainLibraryUbername); + + expect(result).toEqual(result1); + }); + }); + + describe('when contentId does not exist', () => { + it('should throw an error ', async () => { + const { metadata, mainLibraryUbername, params, notExistingContentId, currentUser, error } = setup(); + h5pEditor.saveOrUpdateContentReturnMetaData.mockRejectedValueOnce(error); + await expect( + uc.saveH5pContentGetMetadata(notExistingContentId, currentUser, params, metadata, mainLibraryUbername) + ).rejects.toThrowError(error); + }); + }); +}); diff --git a/apps/server/src/modules/h5p-editor/uc/h5p.uc.ts b/apps/server/src/modules/h5p-editor/uc/h5p.uc.ts new file mode 100644 index 00000000000..1aacd9e7adc --- /dev/null +++ b/apps/server/src/modules/h5p-editor/uc/h5p.uc.ts @@ -0,0 +1,269 @@ +import { H5PAjaxEndpoint, H5PEditor, H5PPlayer, H5pError, IContentMetadata, IUser } from '@lumieducation/h5p-server'; +import { + BadRequestException, + HttpException, + Injectable, + InternalServerErrorException, + NotFoundException, +} from '@nestjs/common'; +import { ICurrentUser } from '@src/modules/authentication'; +import { Request } from 'express'; +import { Readable } from 'stream'; + +import { AjaxGetQueryParams, AjaxPostBodyParams, AjaxPostQueryParams } from '../controller/dto'; + +@Injectable() +export class H5PEditorUc { + constructor(private h5pEditor: H5PEditor, private h5pPlayer: H5PPlayer, private h5pAjaxEndpoint: H5PAjaxEndpoint) {} + + /** + * Returns a callback that parses the request range. + */ + private getRange(req: Request) { + return (filesize: number) => { + const range = req.range(filesize); + + if (range) { + if (range === -2) { + throw new BadRequestException('invalid range'); + } + + if (range === -1) { + throw new BadRequestException('unsatisfiable range'); + } + + if (range.length > 1) { + throw new BadRequestException('multipart ranges are unsupported'); + } + + return range[0]; + } + + return undefined; + }; + } + + private mapH5pError(error: unknown) { + if (error instanceof H5pError) { + return new HttpException(error.message, error.httpStatusCode); + } + + return new InternalServerErrorException({ error }); + } + + public async getAjax(query: AjaxGetQueryParams, currentUser: ICurrentUser) { + const user = this.changeUserType(currentUser); + + try { + const result = await this.h5pAjaxEndpoint.getAjax( + query.action, + query.machineName, + query.majorVersion, + query.minorVersion, + query.language, + user + ); + + return result; + } catch (err) { + throw this.mapH5pError(err); + } + } + + public async postAjax( + currentUser: ICurrentUser, + query: AjaxPostQueryParams, + body: AjaxPostBodyParams, + files?: Express.Multer.File[] + ) { + const user = this.changeUserType(currentUser); + + try { + const filesFile = files?.find((file) => file.fieldname === 'file'); + const libraryUploadFile = files?.find((file) => file.fieldname === 'h5p'); + + const result = await this.h5pAjaxEndpoint.postAjax( + query.action, + body, + undefined, // Todo: Language + user, + filesFile && { + data: filesFile.buffer, + mimetype: filesFile.mimetype, + name: filesFile.originalname, + size: filesFile.size, + }, + query.id, + undefined, // TODO: Translation callback + libraryUploadFile && { + data: libraryUploadFile.buffer, + mimetype: libraryUploadFile.mimetype, + name: libraryUploadFile.originalname, + size: libraryUploadFile.size, + }, + undefined // TODO: HubID? + ); + + return result; + } catch (err) { + throw this.mapH5pError(err); + } + } + + public async getContentParameters(contentId: string, currentUser: ICurrentUser) { + const user = this.changeUserType(currentUser); + + try { + const result = await this.h5pAjaxEndpoint.getContentParameters(contentId, user); + + return result; + } catch (err) { + throw new NotFoundException(); + } + } + + public async getContentFile( + contentId: string, + file: string, + req: Request, + currentUser: ICurrentUser + ): Promise<{ + data: Readable; + contentType: string; + contentLength: number; + contentRange?: { start: number; end: number }; + }> { + const user = this.changeUserType(currentUser); + + try { + const { mimetype, range, stats, stream } = await this.h5pAjaxEndpoint.getContentFile( + contentId, + file, + user, + this.getRange(req) + ); + + return { + data: stream, + contentType: mimetype, + contentLength: stats.size, + contentRange: range, // Range can be undefined, typings from @lumieducation/h5p-server are wrong + }; + } catch (err) { + throw new NotFoundException(); + } + } + + public async getLibraryFile(ubername: string, file: string) { + try { + const { mimetype, stats, stream } = await this.h5pAjaxEndpoint.getLibraryFile(ubername, file); + + return { + data: stream, + contentType: mimetype, + contentLength: stats.size, + }; + } catch (err) { + throw new NotFoundException(); + } + } + + public async getTemporaryFile( + file: string, + req: Request, + currentUser: ICurrentUser + ): Promise<{ + data: Readable; + contentType: string; + contentLength: number; + contentRange?: { start: number; end: number }; + }> { + const user = this.changeUserType(currentUser); + + try { + const { mimetype, range, stats, stream } = await this.h5pAjaxEndpoint.getTemporaryFile( + file, + user, + // @ts-expect-error 2345: Callback can return undefined, typings from @lumieducation/h5p-server are wrong + this.getRange(req) + ); + + return { + data: stream, + contentType: mimetype, + contentLength: stats.size, + contentRange: range, // Range can be undefined, typings from @lumieducation/h5p-server are wrong + }; + } catch (err) { + throw new NotFoundException(); + } + } + + public async getH5pPlayer(currentUser: ICurrentUser, contentId: string): Promise { + // TODO: await this.checkPermission... + const user = this.changeUserType(currentUser); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const h5pPlayerHtml: string = await this.h5pPlayer.render(contentId, user); + return h5pPlayerHtml; + } + + public async getH5pEditor(currentUser: ICurrentUser, contentId: string, language: string): Promise { + // If contentId is undefined, a new H5P content will be created. + // TODO: await this.checkPermission... + const user = this.changeUserType(currentUser); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const createdH5PEditor: string = await this.h5pEditor.render(contentId, language, user); + + return createdH5PEditor; + } + + public async deleteH5pContent(currentUser: ICurrentUser, contentId: string): Promise { + // TODO: await this.checkPermission... + const user = this.changeUserType(currentUser); + let deletedContent = false; + try { + await this.h5pEditor.deleteContent(contentId, user); + deletedContent = true; + } catch (error) { + deletedContent = false; + throw new Error(error as string); + } + + return deletedContent; + } + + public async saveH5pContentGetMetadata( + contentId: string, + currentUser: ICurrentUser, + params: unknown, + metadata: IContentMetadata, + mainLibraryUbername: string + ): Promise<{ id: string; metadata: IContentMetadata }> { + // TODO: await this.checkPermission... + const user = this.changeUserType(currentUser); + + const newContentId = await this.h5pEditor.saveOrUpdateContentReturnMetaData( + contentId, // Typings are wrong + params, + metadata, + mainLibraryUbername, + user + ); + + return newContentId; + } + + private changeUserType(currentUser: ICurrentUser): IUser { + // TODO: declare IUser (e.g. add roles, schoolId, etc.) + const user: IUser = { + canCreateRestricted: false, + canInstallRecommended: false, + canUpdateAndInstallLibraries: false, + email: '', + id: currentUser.userId, + name: '', + type: '', + }; + return user; + } +} diff --git a/apps/server/static-assets/h5p/core/LICENSE.txt b/apps/server/static-assets/h5p/core/LICENSE.txt new file mode 100644 index 00000000000..20d40b6bcec --- /dev/null +++ b/apps/server/static-assets/h5p/core/LICENSE.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/apps/server/static-assets/h5p/core/README.txt b/apps/server/static-assets/h5p/core/README.txt new file mode 100644 index 00000000000..95aa16f296b --- /dev/null +++ b/apps/server/static-assets/h5p/core/README.txt @@ -0,0 +1,14 @@ +This folder contains the general H5P library. The files within this folder are not specific to any framework. + +Any interaction with an LMS, CMS or other frameworks is done through interfaces. Platforms need to implement +the H5PFrameworkInterface(in h5p.classes.php) and also do the following: + + - Provide a form for uploading H5P packages. + - Place the uploaded H5P packages in a temporary directory + +++ + +See existing implementations for details. For instance the Drupal H5P module located at drupal.org/project/h5p + +We will make available documentation and tutorials for creating platform integrations in the future. + +The H5P PHP library is GPL licensed due to GPL code being used for purifying HTML provided by authors. diff --git a/apps/server/static-assets/h5p/core/doc/spec_en.html b/apps/server/static-assets/h5p/core/doc/spec_en.html new file mode 100644 index 00000000000..de6ddf077ae --- /dev/null +++ b/apps/server/static-assets/h5p/core/doc/spec_en.html @@ -0,0 +1,168 @@ +

Overview

+

H5P is a file format for content/applications made using modern, open web technologies (HTML5). The format enables easy installation and transfer of applications/content on different CMSes, LMSes and other platforms. An H5P can be uploaded and published on a platform in mostly the same way one would publish a Flash file today. H5P files may also be updated by simply uploading a new version of the file, the same way as one would using Flash.

+

H5P opens for extensive reuse of code and wide flexibility regarding what may be developed as an H5P.

+

The system uses package files containing all necessary files and libraries for the application to function. These files are based on open formats.

+

Overview of package files

+

Package files are normal zip files, with a naming convention of <filename>.h5p to distinguish from any random zip file. This zip file then requires a specific file structure as described below.

+

There will be a file in JSON format named h5p.json describing the contents of the package and how the system should interpret and use it. This file contains information about title, content type, usage, copyright, licensing, version, language etc. This is described in detail below.

+

There shall be a folder for each included H5P library used by the package. These generic libraries may be reused by other H5P packages. As an example, a multi-choice question task may be used as a standalone block, or be included in a larger H5P package generating a game with quizzes.

+

Package file structure

+

A package contains the following elements:

+
    +
  1. A mandatory file in the root folder named h5p.json
  2. +
  3. An optional image file named h5p.jpg. This is an icon or an image of the application, 512 × 512 pixels. This image may be used by the platform as a preview of the application, and could be included in OG meta tags for use with social media.
  4. +
  5. One content folder, named content. This will contain the preset configuration for the application, as well as any required media files.
  6. +
  7. One or more library directories named the same as the library's internal name.
  8. +
+

h5p.json

+

The h5p.json file is a normal JSON text file containing a JSON object with the following predefined properties.

+

Mandatory properties:

+
    +
  • title - Name of the package. Would typically be used as header for a page displaying the package.
  • +
  • language - Standard language code. Use 'en' for english, 'nb' for norwegian "bokmål". Neutral content use "und".
  • +
  • machineName - Machine readable name of the library. This is the name that will be used for the library folder in the package too.
  • +
  • preloadedDependencies - Libraries that must be loaded on init. Specified as a list of objects with machineName, majorVersion and minorVersion. One would normally list all dependencies here to allow the platform displaying the package to merge JS and CSS files before returning the page.
  • +
  • embedTypes - List of ways to embed the package in the web page. Currently "div" and "iframe" are supported.
  • +

Optional properties:

+
  • contentType - Textual description of the type of content.
  • +
  • description - Textual description of the package.
  • +
  • author - Name of author.
  • +
  • license - Code for the content license. Use the following Creative Commons codes: cc-by, cc-by-sa, cc-by-nd, cc-by-nc, cc-by-nc-sa, cc-by-nc-nd. In addition for public domain: pd, and closed license: cr. More may be added later.
  • +
  • dynamicDependencies - Libraries that may be loaded dynamically during execution.
  • +
  • width - Width of the package content in cases where the package is not dynamically resizable.
  • +
  • height - Height of the package content.
  • +
  • metaKeywords - Suggestion for keywords for the application, as a string. May be used for OG meta tags for social media.
  • +
  • metaDescription - Suggestion for application metaDescription. May be used for OG meta tags for social media.
  • +
+

Eksempel på h5p.json:

+{
+ "title": "Biologi-spillet",
+ "contentType": "Game",
+ "utilization": "Lær om biologi",
+ "language": "nb",
+ "author": "Amendor AS",
+ "license": "cc-by-sa",
+ "preloadedDependencies": [
+ {
+ "machineName": "H5P.Boardgame",
+ "majorVersion": 1,
+ "minorVersion": 0
+ }, {
+ "machineName": "H5P.QuestionSet",
+ "majorVersion": 1,
+ "minorVersion": 0
+ }, {
+ "machineName": "H5P.MultiChoice",
+ "majorVersion": 1, "minorVersion": 0
+ }, {
+ "machineName": "EmbeddedJS",
+ "majorVersion": 1,
+ "minorVersion": 0
+ } ],
+ "embedTypes": ["div", "iframe"],
+ "w": 635,
+ "h": 500
+}
+

The content folder

+

Contains all the content for the package and its libraries. There shall be no content inside the library folders. The content folder shall contain a file named content.json, containing the JSON object that will be passed to the initializer for the main package library.

+ +

Content required by libraries invoked from the main package library will get their contents passed from the main library. The JSON for this will be found within the main content.json for the package, and passed during initialization.

+ +

Library folders

+ +

A library folder contains all logic, stylesheets and graphics that will be common for all instances of a library. There shall be no content or interface text directly in these folders. All text displayed to the end user shall be passed as part of the library configuration. This make the libraries language independent.

+ +

The root of a library folder shall contain a file name library.json formatted similar to the package's hp5.json, but with a few differences. The library shall also have one or more images in the root folder, named library.jpg, library1.jpg etc. Image sizes 512px × 512px, and will be used in the H5P editor tool.

+ +

Libraries are not allowed to modify the document tree in ways that will have consequences for the web site or will be noticeable by the user without the library explicitly being initialized from the main package library or another invoked library.

+ +

The library shall always include a JavaScript object function named the same as the defined library machineName (defined in library.json and used as the library folder name). This object will be instantiated with the library options as parameter. The resulting object must contain a function attach(target) that will be called after instantiation to attach the library DOM to the main DOM inside target

+ +

Example

+

A library called H5P.multichoice would typically be instantiated and attached to the page like this:

+var multichoice = new H5P.multichoice(contentFromJson, contentId);
+multichoice.attach($multichoiceContainer);
+ +

library.json

+

Mandatory properties:

+
    +
  • title - Human readable name of the library. May be used in the H5P editor and overviews of installed libraries.
  • +
  • majorVersion - Version major number. (The x in x.y.z). Positive integer.
  • +
  • minorVersion - Version minor number. (The y in x.y.z). Positive integer.
  • +
  • patchVersion - Version patch number. (The z in x.y.z). Positive integer. The system will automatically update to the latest patchVersion installed for all packages that use the library with the same major and minor version number. A new patch version must therefore not change any behaviour of the library, only fix errors.
  • +
  • machineName - Machine readable name for the library. Same as the folder name used.
  • +
  • preloadedJs - List of path to the javascript files required for the library. At least one file need to be present (the one defining the library object). Paths are relative to the library root folder.
  • +
+

Optional properties:

+
    +
  • author - Author name as text.
  • +
  • license - Code describing the library license. Use the following creative commons codes: cc-by, cc-by-sa, cc-by-nd, cc-by-nc, cc-by-nc-sa, cc-by-nc-nd. In addition use pd for public domain, and cr for closed source
  • +
  • description - Textual description of the library.
  • +
  • preloadedDependencies - Libraries that need to be loaded for this library to work. Specified as a list of objects with machineName, majorVersion and minorVersion for the required libraries.
  • +
  • dynamicDependencies - Libraries that may be loaded dynamically during library execution. Specified as a list of objects like preloadedDependencies above.
  • +
  • preloadedCss - List of paths to CSS files to be loaded with the library. Paths are relative to the library root folder.
  • +
  • w - Width in pixels for libraries that use a fixed width. Mandatory if the library shall be embedded in an iframe (see embedTypes below).
  • +
  • h - Height in pixels for libraries that use a fixed height. Mandatory if the library shall be embedded in an iframe (see embedTypes below).
  • +
  • embedTypes - List of possible ways to embed the package in the page. Available values are div and iframe.
  • +
+

Eksempel på library.json:

+{
+ "title": "Boardgame",
+ "description": "The user is presented with a board with several hotspots. By clicking a hotspot he invokes a mini-game.",
+ "majorVersion": 1,
+ "minorVersion": 0,
+ "patchVersion": 6,
+ "runnable": 1,
+ "machineName": "H5P.Boardgame",
+ "author": "Amendor AS",
+ "license": "cc-by-sa",
+ "preloadedDependencies": [
+ {
+ "machineName": "EmbeddedJS",
+ "majorVersion": 1,
+ "minorVersion": 0
+ }, {
+ "machineName": "H5P.MultiChoice",
+ "majorVersion": 1,
+ "minorVersion": 0
+ }, {
+ "machineName": "H5P.QuestionSet",
+ "majorVersion": 1,
+ "minorVersion": 0
+ } ],
+ "preloadedCss": [ {"path": "css/boardgame.css"} ],
+ "preloadedJs": [ {"path": "js/boardgame.js"} ],
+ "w": 635,
+ "h": 500 }
+ +

Allowed file types

+

Files that require server side execution or that cannot be regarded an open standard shall not be used. Allowed file types: js, json, png, jpg, gif, svg, css, mp3, wav (audio: PCM), m4a (audio: AAC), mp4 (video: H.264, audio: AAC/MP3), ogg (video: Theora, audio: Vorbis) and webm (video VP8, audio: Vorbis). Administrators of web sites implementing H5P may open for accepting further formats. HTML files shall not be used. HTML for each library shall be inserted from the library scripts to ease code reuse. (By avoiding content being defined in said HTML).

+

API functions

+

The following JavaScript functions are available through h5p:

+
    +
  • H5P.getUserData(namespace, variable)
  • +
  • H5P.setUserData(namespace, variable, data)
  • +
  • H5P.getUserStart(namespace)
  • +
  • H5P.setUserStop(namespace)
  • +
  • H5P.deleteUserData(namespace, variable)
  • +
  • H5P.getGlobalData(namespace, variable)
  • +
  • H5P.setGlobalData(namespace, variable, data)
  • +
  • H5P.deleteGlobalData(namespace, variable)
  • +
+

I tillegg er følgende api funksjoner tilgjengelig via ndla:

+
    +
  • H5P.setUserScore(contentId, score, maxScore)
  • +
+

Best practices

+

H5P is a very open standard. This is positive for flexibility. Most content may be produces as H5P. But this also allows for bad code, security weaknesses, code that may be difficult to reuse. Therefore the following best practices should be followed to get the most from H5P:

+
    +
  • Think reusability when creating a library. H5P support dependencies between libraries, so the same small quiz-library may be used in various larger packages or libraries.
  • +
  • H5P supports library updates. This enables all content using a common library to be updated at once. This must be accounted for when writing new libraries. A library should be as general as possible. The content format should be thought out so there are no changes to the required content data when a library is updated. Note: Multiple versions of a library may exists at the same time, only patch level updates will be automatically installed.
  • +
  • An H5P should not interact directly with the containing web site. It shall only affect elements within its own generated DOM tree. Elements shall also only be injected within the target defined on initialization. This is to avoid dependencies to a specific platform or web page.
  • +
  • Prefix objects, global functions, etc with h5p to minimize the chance of namespace conflicts with the rest of the web page. Remember that there may also be multiple H5P objects inserted on a page, so plan ahead to avoid conflicts.
  • +
  • Content should be responsive.
  • +
  • Content should be WCAG 2 AA compliant
  • +
  • All generated HTML should validate.
  • +
  • All CSS should validate (some browser specific non-standard CSS may at times be required)
  • +
  • Best practices for JavaScript, HTML, etc. should of course also be followed when writing an H5P.
  • +
diff --git a/apps/server/static-assets/h5p/core/fonts/h5p-core-23.eot b/apps/server/static-assets/h5p/core/fonts/h5p-core-23.eot new file mode 100644 index 0000000000000000000000000000000000000000..0bd4becbb819f256ecabb923a196f554165c4705 GIT binary patch literal 9188 zcmcgyd2n3CneXdeGxKKV&GkleNOMRtI!BsYvSmrObzqM82qwnCHUeaufF#G*;m#VI z@&X3J5!MOikb|(B#cWtMo61&&N?chsAyuggAvjyhR+bc52#^X;?52|4#N++-n~^M2 zK=MawpI-O-`s=U1zP_t_^q*NmMv*9C4cRxanNHq-{P&-%-}RyN(b)*-NTq z9~mH5l0~wg%z?y9w&1&m93OnXkV}BsPp%_ZgKB}KNRbqf-n%`}vQsxXL^v7R z_~F5lFQ68Hc^c{RE9YnTJ@?M1Dj-Ur{HZ;&*X_gCkMbAs)%RR`$SUI`^@WsGpEm-kqm&Jd*$9&$!m82fA8zW!P7Iph$$+w~&0#zSz$j`Rome=wO0~vkhnNhakjPphN6*SZ~Xx(Pd zjGiH~nr#3e>A}lG4`ZKhS~Hi15`))V_$lB zX6EaE?B!c$@Ek|F1W6X0bl!RA$t9-bGGuv^`~$k?VtVx8R(!WQ zG+$w7utv}gn$f&eQ|*x5PVII~lc&pL*0MG|H7H zRL@U69UWUM<=Q|lSNHj`QBpGhK>nHw_N23h{mbJDH^)^jIisi+E6riZl?-O99GVV?LgDG5!P-i=ciXnxzfmq99aPwpt=gf%nNT&tH@;K( za{0wUY$*ibtDLgGBYBu7(v`2(YdOptf2!vEMX*YdQeCEDTEwvO_;h7*)k>{giiAUI zw#ey1+;Dj#c2};i|B`$@-YTuSZ`GpEm9$PpKA=W3*Emul5~C0Eq)xr~p>s(KeVXrV~C zUaA%Ic3pCibvC!s7EfDgIwurmkI>xeo(m>~A#5SWd+3{jxivAb(89Q)*g%hWXN4-} zg&t6{<1Mo8Mo^)WOtAT>ae=0WnCN+eJ>Px$FuRql0T1w=7j(~fi_1u+TLBkE^Q`3Z zOQ*BFf@WGw#=A31Wb@}Q_eKvjO!{AqDuqRdd|gd`!;i7cp`EM9F0598Lb$Wq7%i`& z*f@wk_Ri6ToK~)uOH%Hum0Z3ETptBuiKM7xR4rf6Lb0~DgM$Pup>`<0Mfo0+z68Kq7WV z4HqGMwR&^0WCipE&74Uh)y$-kC@mgoe8irb6$l$ z*luG}^qv58YS5U7=n>b-t$Ec~MrODrA5wv1;7#3pL;uSrLz@Mh0D* z)rg`gE+f+8)xp~%9*dOh*kGJ0=uz#Q09 zA}IT3syF0SeBwuj=G9}S;x**3J*L-ENYv0d%G@VB_7zx4HWnda*maD)R z%B)s``IDKfwi&4p4Nk+Ogl2{YtJT3FIE_$fdT^+IkD{a%pRsWxb}g+a7jG0IBmDaL zt@6f=?8$I=W)O|wX~KBmX~00jjVGX@86nWtX|oA!bd{g_eZ~B07$!1=<6d3fTM`=7SXaIe!q-q*@N!C3MFB(ylv2Gf8`|W2Daby3VCqL%} zb`Y`c2=>37CTU15!qlvx75KkeM3%#j`|FZUtyxio^0z8-O+xw|D8nzIc`F_g0Ws z$ai_1J?QxGHROCLt7_9FW2@3OoJSupNm_=%^ijvEAtr;ll4EXG!9Ax-HH;TdU0E4< z&{=C?N~m^P-%?>S|9;s|P&DnKI%^)*exH2|^SPm#;{YW60)`80ZM zIwMsYbNRv(HN95>N-q5k;1Z6!j!{Z9JOjmQI-VYmgZ5W0@9FDsF`>>ZObea2 zCkpYQ(0Ly}PjPAey*+D#Axd>4R*veH+ihuZ6D~K5Gv|~(7!L$uF(me;4j-U7rBp`hA%9caAvq%rCe?xln=&AF?QVd zG6RqO14N=3>7Fy$Q5lrL?a6o;?~-f8Wa^Ofk`v67Ly_>ZFCGfPZAxK?zUXFsdg zhZm73g#+qNat-k|4QIS|2&aqT`XUl#TyYn2T*boDjsdUXLSSA1Y#83Y6r+r3UNzG0 z(skC~*T1d5zn?Of%k1qy6@?9nW!;c(pi$M=_*Hp#nJZimxe*?L!1AU$H9CIF7}Hc& zGGtn^7wR)rpK5rugN!p*%+)@U$ghi`nXIE$U#x$&tojr*PpppDw`ZC)vB_TSoiFR_ zhtE&cV_m~O%9+{bfk?ne1&T>~uuU^Hc*#VqEnD--+L(u9oC>ol9r1bsWRyON=4M#e zBYxGTnlUrn;j-8FQBHmB-nP6~ZwqjpdlTMZ!lk-ZBkXbXj*!Q3o;~5{T}U3*WR`&? zgT;{MY_;6q)wBfTC(kCFguTbY-f3_6m@gFaEraw9U+A;maM=6VkZ4wG$)3Qu@$dh#S-J*!ykjTb=JR=m!x3^y^1ZSL z41||_fqU3PB!)GDEh;%C$T33l%;=mRD^gpPrfq~8!Rg3jkS0F-m?JKMc{t$Z}}md@patWl*wg?sm7>n6{yD39Orxs-XsVMiF00o zW?|g;Pz2j2cU2yKzwZ%qKE}ttq zmGXCmCOR+312WCjR5pJ>=juo{NQ23Ep2o7SRO4AXn$&ZRmve0~dW9X+q;ux&c4Jga zggh#bx3$4Zd4oxvKHIp)AK)Q8-0L??P9F(|xQVFVGkC)abdYMw=3ZPn8pOXLD1_Fdx|fMzu3P0W^t0cIo^|k#TF-nrKBt4 zN7MVIO5&D_KcEI&o{*Xxj*ZFgFAP*x!kon8myL~2OCE7NlHc^$_+|0<>HX0*$z=i@ z+oBFU(d5WV!O-MDpYP*xMN?KIqflaC?jw1h?D$InaNV2Jub2X!|{ zP+vHUM{prD5IOeYS#m8OX0MYdqutC3ZPGFi+3)5T>1JmIok zmFF%;4VngWg^jIaMIGCVxGZeZyDlhBmvSC6ZGVcg&M2*?3}c|9z1MJcIM%Z`&CV;{ zZyT5YV*(=!?f z^mWdB|ANN$zD_h5bZY8jgFW4A0{HPn+Utokr}#F%=5dN2!Y@?v z{&tXzlJm$`tT-->myU59LWJPSxkZ$r)e@{Yu~V}suhN$A+4PFS$_81stq=2IxBVy)5Q|N15r7BatXz|B_vTJP7PYpPcAidc%sSuOPwrzS$v6D z&RHd2BK>?9?}0AmpiR@zrahRk95r-hNuO|@jo7$H#ihP89Y;T49L^~PTaC&^oPL)g z7tB8=HBxd2Tg5OxrwQBB`0ntgWR#0)7aenlU6X-TnbkjbdpzzR8$Q#$4E0L7O~Z6d z=9gBw8sF`z$|hZvdzWc=&&H9)z3JiLj2?8+{asa6iFKTQ+2eM5OqbhpqXcB4y^_vh zw|`_~!{u;Vka^=#i%u<(L9WlPO)qKQ1-#$7*niU8@r#ybYj)kP=j-n|^?mO<&5tD( z<`WAGiTQ>2{K9+A^yUwmRWd$5A7A2teHY|78R1v*gmWJ=g_|p!V4aOx-MUQfkVg{u zR?UL+r#Yev$b-DssF&s54xT;CX!R8$E|2VZVsZ6%RZHGgp81{2BoA&hBjiX)F-VTc%jP!WIfo!pu_4;=u!eA5%CEGQR zhFh{tBaOQ zGRUL+ZJD+`yiR%N=q}&rZ-`qudP4r~XOG`?_S>?~_+J3Tzs(2joZr+T(DLD@98S%; zX5QVbX%=KNl;049-iid+Nr!S`ET=f^KI`9zKCxa z9OZg;Qy*?I<+HR}PN9`~$=6zIMX{dE7LroKsZ_R>ak)|rN&k2YR)PPU7VLsgD($WA8@O_D z|J=L(C1rYX;XrE7+``=c*#mP|rLMR!wc*Oeixw9b3h-m{-%$>b6uj9SAo))!vnbEu zhCW5EAU7i4;QVXLMWB?lg-ho4Uw8H5LaJCOzW0B%yx%b155Hw@&%tYF_n-SuGw(<2 Lthcl5@0a}_;rM93 literal 0 HcmV?d00001 diff --git a/apps/server/static-assets/h5p/core/fonts/h5p-core-23.svg b/apps/server/static-assets/h5p/core/fonts/h5p-core-23.svg new file mode 100644 index 00000000000..6196c94271d --- /dev/null +++ b/apps/server/static-assets/h5p/core/fonts/h5p-core-23.svg @@ -0,0 +1,62 @@ + + + + + + +{ + "fontFamily": "h5p-core", + "description": "Font generated by IcoMoon.", + "majorVersion": 1, + "minorVersion": 1, + "version": "Version 1.1", + "fontId": "h5p-core", + "psName": "h5p-core", + "subFamily": "Regular", + "fullName": "h5p-core" +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/apps/server/static-assets/h5p/core/fonts/h5p-core-23.ttf b/apps/server/static-assets/h5p/core/fonts/h5p-core-23.ttf new file mode 100644 index 0000000000000000000000000000000000000000..e793b63af33e815edf5487888bfdf4880f846219 GIT binary patch literal 9020 zcmcgyd5~MhneXdelAfd|>FH^7%;=br=G2U&ku>9DW^B)a0mnx$F%GsFU~CgSGmf#t zopo@E=`|Bso zct`=sAE~@~-S6w}ufOj8`n$R{gc3r$+7IrZo4qpn#MjW2jv=eBrzlQP_ zlsos&AHMEyNa`O^K8*4g4lG_Vd+huhA0i|ZL3!K!>~#l8m0Bq8M>)MPJ3sf+@`nzg zd>h8N|KQ>^hcQn)IXRy+;rwlSFHs0#pJhKl&8M1Q`b$!whQwR(P)z%s&jcZ_h4`tn zr^p0HLZjrx(vx-pIhssKv^Brn#Yz%E6hnTzULM4>TRgM=QZNi)3ZO1e?ER)Tz779KH(g7Y|vOaw%f6lQ9?l}u%ew2 zQXh5E&-M9Zb+6MjkFpv8UN}QvXZ?-WS*`Ip#-Q|O@+dpTo|J7}7K&7Tl=&L}=e7}Q za>6!B9vf6EXa$CetaZFVhIEl0GC)e0O2y7qS5ssfpgPhY`_f}GGhh2-FW)|c=LFKlNV4Fj^Uga@ zvY3)HUKz-#v2C_vzY;=$%KljMN5)rtL_?o*o*kt%Q4b?6~FY zmCBui3VWi}Iy5*FvF*sr;81ONusCDetTNsB_VAY~FAQQ!Apl?Dl>GxKkSZjoP^;JS zSU3Ju&HamlOVM&&rV(1gvt9^#>IYIDNJh|!b-ATNytj8zh>Y-y5A0sQVfXG0>vt0m zIZmGBSFtY>A8|+yySIu=k!@rbnI&`JSS_E!ENv$eE!8#5Z=7O*R8yk0YJE7L)3R#G z(bPx>l}!b%Mk`LaRxJ$YOIjhH4N%!s?*aua60OwBwNk;UOA4~h;a0}t87o8Qgre*d znpfR-!Gth`BgA+QeM2y>Cgv4d99I+v)#Kecp^AB-hm_oS3$42mR;WZ1Y<_B7psOJ! zdLC!bb)PxLZf0vi1GMJ_-8bH%GMepHKt<7fE2;d#9c;g#*%p!U?(7oU{Q1kH(W4EM z{&%BFVbLL9SCL=yUnrrj zkD_7;rKDt4tx(TFv2zwM?Fuxb`PSP(s)k;Wfg6MUsXIUCHKMu^G};C&%QAGMEvWd# zkqz0hWd#G~ZX;}EyMqy3Xu95b!xz){^zS*cxOn6)(=qgbB6P7wIF_AC*=*bw*iaW5 z`t`P1*`U>C2xi9XilVf~={X40VtH~?W4^AX$2__(`=6Y#vC||`=hO)9oZR&ij0s{axm7^t?h@o-` z#Z|PV)FeYR(;;c1$VlA5ufPP^c$l`h=qE9g`hK%n*9VSce)dM+Iwm%!FxB zVa9}^g4@CfDv)~s!cat~87)Lj?3B&~$eDS+LLX>1y9`NGFkL8`(PkQLei4N3E1<4W zzoEKc)9KulQ>Y3V;7YujFoHr21w~FIqN7LLS#iyKfhJpyqP^=+cSgc1W#k*fu{ih2{#^x zie`mCU$@T|^wCk?zPU+rqYNxz=N~3t4L6){ z%W}WNa4*~KuyhL0h(FOOgzZcLWrtLfaMP#EQBTv@SeiT(A=g420qlClpl~ z!}p-Vl`B7j>>wJ(6nX+^Wq>DO5XSMnLhh{~FO%=^1be{s;cLnHQdZTbOU71Z95|0Y z)TC$y1~WiitA>~i=1R`F*#!5TDc3MxICW)ZcODt4+j0FJcdvjCf{PeVxK`wLZCvekYQOemt&4rOj2O`Zq@ZMEw0~ss~*?JboqTp znV!5AtxFBSk%;=*CgNIv*zYIFWqdVz1KxZZqc)w9Dvh~(;fb2ws|Y2R{s!?|t=@Dr zu4l(AWi>nl1vgz!5640KhcD~t>+mq4&MZs|owp~8iJ{1OA3aa;X#KrC>%tLAbt7Jh z>6X`PX>b!BFN`zils=FMh2n7}_J$Sc?A%rJ_|)lzX+;h?UiP#z@YGba;bHuz>3|e46t=C5uktl@&>P~SD@iw)yekX#{#YlY- zi88Kui+Qesv9x2rZ+H-x7XcfFzc0-wW13%$wtIA)_4oDf=TCS6vbVw&u1CBGkAPtLGo2b8ziEtVswWjOEjbDem})>Z{Mr%5nJ4aPA59k4 z$I(r;QL8WBKU+})3c4p(C+a)1&6fCNFZM2w3-rV1C+qR9kpSh)Z1X`RV5CB&lrz|- znHs!gveuTX`DJU|$1zWZS;HNPdJ<@qK7#J1t?SXC>QT+OX?J*>4Skf;K)b)K;Mdzi zT<89zKb-WaUe&ODuHF&y7|ydNUA>FQ!O^@f4YN)EFsaV1( z_F!jccrcA%Vy?e0)#|YJ(-Y~z@bA>Py2v^AsXqrM=hw--Q^_~TCccsD*t-lFBNvjL z@|MSqkg-8>2dfsgB;1r5z^<&=R#yvx)U@1@?c!H+YQEY9*=k9Zv{JerC9*2!cXWM_VviTx&)8JjBqMz(~*u?+p^NBoxMf5ab(_}&F#mrj=&FG^Z8 zQ<`pEEeX+fnKxc~jHY9mOe`Fhv>HDvPmi-qJZl9cy@0jb^7}&}zyBNnz6jh8{yjg6 zGro>{n+mxUG1VA#tRmHThU1)X!JC9(A#u(t(j1H%ABtl8AIPsQPvp}xdCgMOtJ>nDX-~kDn@R_}A`_h#6ablKdMa1ApmTLJ7pCD< zqCn$0PrC68U6a!DjhFImaeBEE*Q9gi?M`EjmW=pRo@i@>lk$gCI(?>bbuh#uc(^}k zn4CTwj&KuEy=ihg+}N#|9`J~PM<>CflVlio41_AVf?t|<=>eo08OlmSgS&%jy?MsN zX%0pJf>G+KC{TFdXi-&4N8OPJZ0NbeuWj5eUI>PQssRIsoNzMSzC~iW}rsY$y&4 zuY@^CBrY8rpO!QdcqF~)vGGe2i8F^{ZIa3aD7M91c%n&>mBW$AfnsI2I4~KGM8bfF zD}W`in5K!!A8M7Ay;tQ2KZgD zPDRbe-{d}4Qb`5ur6{`oW|+t4=Fkf7am;!2&sVG)sFbM*)=ga#znK0HGX@DcVJi9z}& z$R+1&ri0s&rkxzB)xnLNGL+3>1z0XF6W|G#?W#O?xoXffkSlC#9UOISFXA%WqIXWt}lvPaDQSM|-c~>2R%QX_}o^x*-^g1+7^0nRM)TPR8^NWWJCo8YX*9 z8phr+-<0kIX~xM=7VBJyXS4BTgV|o%XvVByTN}DJcDR-^t~aAX4kJfe+7K)&YfSUCVc=Mwr<;X>9%dx=Q=xc*KgZ)>8@>CLFo4{B$Jn~LzngI zW>d*zYIfavbYFLQGD&|05h6q*eOSk7eiXk@$@|+uvWA>Twu9riG+sK!aR?EDC-)Xn zhE_|k;>J$RqP$95s?TLs6jpY~u^q#mox?KiXnuz2B@*bWRL+dLpRUefr&ZI%lBh?; z@R?IfRlHk5vTD?AK~MVerH(F5bh&S7kfkq6EFsG^tK^HMpYP#4(4{=IX&TzJ4=a|l zhOR8>6V9_y2luGB)OVNT>IaO&J4)eJr%DN@-=)X}>(5J#loV{MWb=1)Vfz~28QGGG zaZ&A}V_w@c8CsQH{Ufi>=lzipFuluAuf*FjLdRr&$#7TWJ6%=TrEB<}WgOnKd9-m) zW+XhLhduOAS5;Nw9cNzhdA&Z<vO#6 zCC$5l_u`B5C#@a7Xlah-)SY^v{;o?u_@2xBNOEC5xv-F&Ur5X^yz5GDe7{wt67%zk zB?{PgK~9iSeg#ju_c2qrxxxw7-Kf>A%j6DuB!O?$EJ%NbBf5Y*$a{@?Megn3xxj*tEy2YE$<~qEN9Vy4LpIh0q zug7WJ*;VcBu;`I!kIxR}N~N4XxF>0YP$ZIS*L)go$+nC(?#QkRO?o0e`mwGm?h$Z~ z`a^!q|0OuGQXu|(?4do$#l_~ESXlhCGpq6Z677Y=;v$U2a{T5+p@3g*4fmH>%C}E8 z-fX-%NrR2ICaFcO$;Mmkn^TQ9sWsJjtMTR(wcHHyD1Td~Z4a$i-oA5BV9l?IS2}t^ z{^O^Q-Er>Qvd;Kl0K~t|2mRdN)FIIF;ip|n&9-LV-E3(VWH*#w7lhu71lUc-Pb`+=w3SYx?g7BhAe}~vN_2~Rly2oF{>A$N?{|Gs-wnS1F>f*7@?RH-21Yjl;FHSxs|N?JSUfa`({Ys?#2NkyvPce*x#`7)!|8o< z3v-8N56@khzWn<1#w!*#EiNt;;l~!q0y#|5@Md#>=72wo@*HmH)8uk;J@Sn%olU@$ zxW$X-4qbEA;zGJqERl=d4%gsEN!gS}P+laZ_nO9g)o+{IcjUnAA^ZY7hglpU2QY&} O?}hC0+hzNEW&aN#?^p2v literal 0 HcmV?d00001 diff --git a/apps/server/static-assets/h5p/core/fonts/h5p-core-23.woff b/apps/server/static-assets/h5p/core/fonts/h5p-core-23.woff new file mode 100644 index 0000000000000000000000000000000000000000..a2f93d0a2128c84634c9d8a2210bf7270cf535c0 GIT binary patch literal 9096 zcmcgyd2n1uneXdeGxKKV&GkleNOMRtI!BsYvSmrOrBR#%AH=~iu^lDIc1R={Cnh(T znDXW(2U$bPgd=2+I7>DQ6k7!aE;b9HiYh{g+1hNep+Y4jVM$V1DA)y$_t$SmvXV*y ze^C4MzJ6bS{q@(^cXapY+Rcpyp#)F%R^oQP zdHkznKZu|mN4{Hvc8tHWf8mF)&!X-7B>b%OfrAH@uD%B2m3?mUabTRkN$(*FA?&m4hsb}b^`*Ze zWojV5`l0^SIf+jZ@=Ac8JadvvaR4Y3u>7PP#AyXs0%a0UAeCGRB8coug!n;GK})^3 z_r*`WL|?xB0IRSnC#k*f3FW(CK-LDXbPS5-z_W9U#G2On!{)Bzl z4!5N`72cL$T_MTmwAw0Sgw)5JuAc4hpQ61=Q#`_I1bo3XeU%M1UuCuCs}M-(&Eyew zggqh4dMsqA`Uvwh|JNxa)Z~P1l5=cOEwAMnIx_y`ljCgD8Rv`ot9Ynw(7Mf@96v*3 zG1~-0@F@@%(r9a3}OZUk~HZdePoCf(Uo#ITU|?$Xu#@#KlPLk@HE(Y4QT+>>4>nn%8War{6nt;ScD#3+Ww)w&T0q;rTK< zgE=aIC!=|(rrII9liCrxn$6@U=>)Y$B1Jo*4$yF|K0)iXd@f(0NEodbM;f6Z_517j z+|Vu;<97&C6L)H=dsl6szvePLhHY=`?<=q;!r@J&Vtsg^e>!R#KlP}OX_PCEsh*#D zy1KSk%C(_fuI}?=p`iQZkK}K-V2?XoXKFeTCM`ZWsQ;A z@JJ&Z3WXaZ!?o3T|BfBEe7#)0V_0F2w@XKcXG7s|Xm)s{Rv9kLhQqAfXnv>irSfyb zSW+m!-*L+Rf#gXQ8kDcqYdMS?f2!vEMKDW|QeDC*Euvd_e0nmuYNb{#MZzI9TjX>x zZn(S=yC*j=cu_tdZ|BzBvt~)?N?NC)`5znh?Afqk_wEhPFZB$9DF-IQZ%2EaTt3#{ zza&Ijc*Xm6Z`ind_r?voiHjT~Pw*?)mx+hiB#YHsLuTN6c9A(Uj~T1wvgl>l4n>M} z4gH&>7$DV@NUd70Y}nJ&(%oTF4d~}O0KBoa~U6%MfDy?&_a=Ny;Lja z?Yfj8%WQ6?EuOa0bY3XRKB2kQedkRHL)b!0_R-e_b8BKjp@m6Bu|b~f%?ed42tA-= zC);ej&7eXhn_vqwlLA!@G1d1Nd#3mF5q2|M2N{sPAn3lywv@3R)4Mz&1x#Vffkf<#8ZJWj zYW3D+$pY95syVN0WSkbAc|;NXPphbi`CLUWuBrl_D$K78`%BO;njKM*X3-AX&*aVy z0iwq!Z?!a1Dof6cY^k3Xq3UwwK|)vSYRxY4MXSfw0|xwPTMc2Eg zyNswI^sb36HByQQ)^wS1)1bnP3PZ(g3&XEK?|}$I5#44aA2G2~Iuj6Q=DZ5Mztik7 zq)@?hp=d^jX>@pnAGWVRxU>SR`+}@ORpu#cRlJdrYsT$bo>_@M6G$P7C7@K4&zlsVP57nyRT<-2uUc!Ua`O zSq_N{H}tb>vKw@RDO8S4FxwO?dx4}W8dX-tr6{5+pm>!?!k|i|i;1}9v?=@IF#ftCm)j3pWdq5q|yLc7F3_ z_INlvJB&(*G+{i5G!P*1=3_9?j1Z{n)Y*bMI`Z2$w`6YGBFEw)50S6(%h<#4^AVCE zgJg_MlP%-%=X9k5}I9*LEfN#PRUj=ug?3S61&l=p4Mz zXO)ohSwW5Fx1RGE4a4`*^I<9%0N@S0ZS*GLH4GMz=`GDiOuyfhz=&ad%XvMw>OP-- z_a}6*8-}TRkn9$^VceydNQ75C;5WT~zt@z<5K4pO+w9luGuV?5m{5Dmu%ekOdye*= zB+vF8)%6K2rXM}3$FvDue&3R(Cyt_Yxd1$pQD4_$Tn7~P{sg&{uVt?xnm5pDD;TNL znadZEs1>~mFmf4huz#!7TY<)j?C7N=BQj9TrW5HAIOt&I(!PN%7Zd92VngV>Gf{|- zgwFZMIf_dg?C)D23{k2Zv2s+m+-^%lm~gq_oH?iT{&*k|iviecman^eSIy;78;cD^ z7r76bhA%9IaAvq%rCe?(ln=&AFQ^ITQ)6#Nv? z4$sTNs_j-Fpj8905wW$kF@i4QMYh&zg(B*=Xih2_+s#D6=<7-!(XUmF=Go8c_0c5& zr3gU1Nv>hPO~VG=EjzTjmPaLvC!3z+idP-5Q;|X@Y60D;Y8^ z*$VZUs!uh%+9Af7E9UAPOXN4iP)(LmYali_S5|!rswdXQ>pL^8lGt=V*3Osp4I<_z z>am_tALY#K@IWQtqyojHJ=~$08lq&P){(7wWogXA(NBe0m9BU_0X9k>Ms+i+>k+@| zQq7nd?sC~12Pmh$PH#uvt9Jyr&b@Fk^Yck2elfh$1 zceYlp?^;@d^OI*2PQu<}VQ<45KIRLBd@Cru)ff7VHyrkUCghtri%Nf`kf+HmUSeVl+xsmKJ&9%Wy6)w! zy_|_WHXkbAxl`rX88mNOtI2JNdbQ>jS95Nv9zO0?V-`KKEG`;6ai!rIxYe|pkJ3%e z6Q*UE^sp!C8n{Ujd!dod|9ny?l<(}kSP0HIE#Ee-N=c@ArKT<6V`|#?ZK~UYiy0^{ z`8@Zq2S^Na1YcBgT#)009cG!9S=mb%}HCQGWqW z&T&~qaF6p1asl7Ob*x>QOpx=*PI=4Y?2xfQas{gvmL%BH8sLtugsq-72CZp_qp-tY z&8oR-4|J=oRnjlKM~*%7`(mR}{C#O=rZkq0{@zZfZ6v3Em5%-{nx2>`{Z5tygV8ko z+QVMU@;>Yhggoznu}d1o=JQe(O&1%@E2SXXDbwZ)kJ3~$osI^BQdaZlrN$&n$1;{r z%JW&fEw48a@OsZ8m={3~lfUPOamLqiZ&N0hU{5tcZL2^vp5{2`TZkq>cu1V{3N#Dn z#z!JpKDny$@FR~rwIb&zgPTJ!Sfy`vPCt-@V-0qaI5B}=ia9lX`^NIe#`5fvnsWlz3v6Rc_%Fd+x zJ)x=Y^YXw57@ACn_t_!O+4oh z_*DZYX2HAhDZ#j~T$P_!}_NFF*aEf#k=jxmQra^z~(datUC%uY<~ipArxT@w?ttMT^$A!QvLxqiUDK-{{Dywl$;_*u+CL2;l9FLUOn3%jI9zT6B+99P(L1IVL z!KYdhSt%Hr9x9Y8g`w$SC=>)vY%J(vM`Xl`9`0I7~tin!^3 zJ|iQ+QROgp4q;@R6LJ~1ZNT4w3)Hh*$lzuU={rb}Wq{SK!n?>;aT=$mKA`AuTzGT^ zD6|58S66O{v_5Akk;qy6D-H@hKnP_uA?r2}{#$YkK^qbm%^yD_WkVp!haJ+LU_p7| zEFGH*p@GTq4^NS+_$YgYM4|mtX?nJGLp$+1Q;$Z6A%ek{Hi>6 zIcCsukgI%b9W(0qUhK=l7QOwvVxyGvm}&cylyygGJ!Kd}U7h`gtIP48#Rfa4c!NJ0 z^;^-%Q>o}5?6m0_N`E0;FiiG}bd3EIo*CWt)3lwYEZV&o%Vc6J4zshk$&6b5jt*3B z?r=P3+8fi-LqlmT=50Rj*!n4Qm=Ca1xWO)Cta3b#wuj5hHW0CKC#G>&Jnp^f@|Mdn zj%v1T7VP=Ht2a*6>RavTc>!x(UtgiTqpR`#^Pg{h-d@N)QmEO{t+m=jp|5W|5E$s5 z{r-8)odeydGVGMpCx-ia*99ze5B_@U%qe~nckP^Xk+ozJyWz5x4Zepd^7pV|j$32; zlbt(3MB=jbsIp=GTr!bJ&aK~o>gz8{BqKkJ7yf0#>>Yz4kg0o$+<<8TdQSUarREFth`EFrf1WuGOH_O*^WwgcSXXE)~7-* zmPk*ze0t3J^mJG3Hl>FpKnJ06`s6Z+_exBX#+(w=q#s+Z=*UEsdzTwo{<8QovmCQZ zzDNf79^MCA%E6i%u%>+&vFtT$W!au^o{iYJN5!SSGaSc0;2hqP3$`nji#Yu*?_4nc zoU}+OA#4@H{4G`3zUFsFwo7l@SX@Xf zE+!Th;|q)LIMN&6YgEbj!a{sm0@huS<7A9q&J)gk%nWX>aDsIfYHj;6xl0~N5L-11 z+MnjwT|gh?y+*w(*LL{qVMeR3QgL}?$17KPmHw>7PgZsM;ON$^qw9sI(3LK^#rk+P z7z(m2qs{LWgOO^EPN$0+4f^B7?jL1~v7dwz$zUj%d=#5`>_i?K+u9jZL^XE}_77uQ zN9m!lE$&n%+vT>yp;8R%xs^3MeRlJXo@#%WMGr;#JmEmLSj>9;dlF#?3WbuLnn%Me z*_N^9?U^-!X;;WYKiX5pJp#^AZ=a8a|Bo42tq^~?>7jjzrKQ#zUtIc&Pge8UW!a1I zr6o9vmHiw3JAmf#%dO%3GE4dP>E`Rr*Qcq!`NlN0s5RYugMD+R`8u^`nr}2;pP`nM zKp*9A%e3Rc4a%E$?D38Nmbhi0C*ie=;VFr(HGIKfB-O{+=h|xxw=r^A__B?{&V2Zxj;c zeD+cwZZYMvJX=ntop{Mt+H*yn|G$tmB&UW`X$$9||5Y0oz<=1r6~xEAZCnNY^KIOP z^L14IZ-FpC@uQ@LGvX!RZsQ#EPqlFY{Mk0H;3oYeZCnNYZ`-&FF{!k_dSK}CrGxW0 z9aqT#oZ&AgOXMJ#Z!9fdliD}GIDc^Nn)wfGGuumX;O^h+|7+kz7Mkh-UM^ z=D|OQ{5)>xQ{*yoJ%I7KOJ$_u3UZryk{ i`nLIfhpw7Ch+lx`(ThXmD)ivsyD?+#aR7R+=l=j~FkgBA literal 0 HcmV?d00001 diff --git a/apps/server/static-assets/h5p/core/images/h5p.svg b/apps/server/static-assets/h5p/core/images/h5p.svg new file mode 100644 index 00000000000..07191aa8b2a --- /dev/null +++ b/apps/server/static-assets/h5p/core/images/h5p.svg @@ -0,0 +1,16 @@ + + + + + + + + + diff --git a/apps/server/static-assets/h5p/core/images/throbber.gif b/apps/server/static-assets/h5p/core/images/throbber.gif new file mode 100644 index 0000000000000000000000000000000000000000..acddb91dacf5380214216e7ff2e063f6e5e60d5f GIT binary patch literal 1638 zcmY+@c}x>o90%~3c6tq^Gqi;koYD(=*=q{a3RnT59MaliTR96Nmcw%Bx~^-Ci?2wG zz8GVSy2cozhCo9M;qU;L5K!ZyF|ILcj4{Tz#u(QaLx^ik*qXR2``(}L_s1u{@As9K zyBw=GlL(0{GLTp-cI(!yU@$m8KmYmj=hv@a-@kwV(xpq`aJad-`Q5vB{r&w53kzq? zoSB@Qym#;3+qZ9z969pn(W9qNpMLo8L8sGcG@378zC3vFps1**s;X*uc=+STkBf_o zr%#{0eED)$SJ#_2Zw3YiK7IOh@ZiDQw{Mq~l|6g*?B&asqobovr_<~8UcGwt*s)_R zEiErzyf}aU{QLLsGcq#L)6;8fYlTAL$jHd<-MeRIW^6W_*=)Xe@ge|VdV2c#^XL2a z?c;K}M~@!m^Z6AO6-`Y|yLRo8N~I|&DSP+s4TVA;k4L3aS*=zGVP9Wgc6RoO6DJ-% ze28HfMNu6c9fuAbdiCm+!COqv17;h_;_1en^-J%xm>xq zxdjCUy}i9XJw1NEU!hP$B9Wz~C1lxAE+u$M{2SL5dP{6(D-(@BDgVZJIKn`TU&p@2 zRKS6~3=r)*03w}qKadbo;EQZ@_hUFNi3-ZMCbIc5t;5Q(9I)m6T(`cFoY&> zR0y>Gl}NwP9-{izlyMbZAKDmy&hXl}apHeK6hRR|{34ua94Kt6-ke;K!3L1Ca+58~ zmD9E%5$aP{*9mY^Z?4G!qT+2QA@IPwNW##Fgi+VnJ~E`niqphbAVqPrscC@I0UmKv z&7yn!)|;eL91N7KxuW!0Fb30;-=kHlm9?2{8WM>~-d02(?jT11$L)$$?ZUl$88 zE_bnjHm`eK#O(C}7*;e!44sw98WnVy8HMdM9WGg)Y-Q=z@;DF{y0)>6{)Sl0U!URa zmX1Mvk;YTUp8{mF%bhQqi**G=cVMO|deLn5J0#iqn)h9Q-Mkcl1# zgbf?ggv=y)ELNA?r1xsapkRHqszE&k@Qs^RsAlKL(v%Q~HHYZy8%1*I171x6mFdvU zRaFv*GLxy}1Ib@VI>c*zS{*5tVN+_H#lrauG>&~s@_(|vxD4-DVR9!5f&gmm>83z_ zUAHF$Eu6fNQzrA}ZTGK1CQsF!x1cD; zm6fuRGe#t=vn4Z3!tYVW|K|6K^~S3&5eJ1*VSLq4OgNGsoW4zShaBf*JZ`~h%QI{(u)FAqNZq?!lDq9 zQ8>$D5l0gtP~){i93?87PXUsU$`WdL7l1ZoX>79(qj;EU%OS@xy)oG}HLOPLj4b)M zrBz_EZ5bDM318#p^b4VYb!x@77EimFB2;AocGSK#Rg;!&R=7J(iL9&2xdC}Fx*y5= E2RJh7g8%>k literal 0 HcmV?d00001 diff --git a/apps/server/static-assets/h5p/core/js/h5p-action-bar.js b/apps/server/static-assets/h5p/core/js/h5p-action-bar.js new file mode 100644 index 00000000000..608a848b3d9 --- /dev/null +++ b/apps/server/static-assets/h5p/core/js/h5p-action-bar.js @@ -0,0 +1,100 @@ +/** + * @class + * @augments H5P.EventDispatcher + * @param {Object} displayOptions + * @param {boolean} displayOptions.export Triggers the display of the 'Download' button + * @param {boolean} displayOptions.copyright Triggers the display of the 'Copyright' button + * @param {boolean} displayOptions.embed Triggers the display of the 'Embed' button + * @param {boolean} displayOptions.icon Triggers the display of the 'H5P icon' link + */ +H5P.ActionBar = (function ($, EventDispatcher) { + "use strict"; + + function ActionBar(displayOptions) { + EventDispatcher.call(this); + + /** @alias H5P.ActionBar# */ + var self = this; + + var hasActions = false; + + // Create action bar + var $actions = H5P.jQuery('
    '); + + /** + * Helper for creating action bar buttons. + * + * @private + * @param {string} type + * @param {string} customClass Instead of type class + */ + var addActionButton = function (type, customClass) { + /** + * Handles selection of action + */ + var handler = function () { + self.trigger(type); + }; + H5P.jQuery('
  • ', { + 'class': 'h5p-button h5p-noselect h5p-' + (customClass ? customClass : type), + role: 'button', + tabindex: 0, + title: H5P.t(type + 'Description'), + html: H5P.t(type), + on: { + click: handler, + keypress: function (e) { + if (e.which === 32) { + handler(); + e.preventDefault(); // (since return false will block other inputs) + } + } + }, + appendTo: $actions + }); + + hasActions = true; + }; + + // Register action bar buttons + if (displayOptions.export || displayOptions.copy) { + // Add export button + addActionButton('reuse', 'export'); + } + if (displayOptions.copyright) { + addActionButton('copyrights'); + } + if (displayOptions.embed) { + addActionButton('embed'); + } + if (displayOptions.icon) { + // Add about H5P button icon + H5P.jQuery('
  • ').appendTo($actions); + hasActions = true; + } + + /** + * Returns a reference to the dom element + * + * @return {H5P.jQuery} + */ + self.getDOMElement = function () { + return $actions; + }; + + /** + * Does the actionbar contain actions? + * + * @return {Boolean} + */ + self.hasActions = function () { + return hasActions; + }; + } + + ActionBar.prototype = Object.create(EventDispatcher.prototype); + ActionBar.prototype.constructor = ActionBar; + + return ActionBar; + +})(H5P.jQuery, H5P.EventDispatcher); diff --git a/apps/server/static-assets/h5p/core/js/h5p-confirmation-dialog.js b/apps/server/static-assets/h5p/core/js/h5p-confirmation-dialog.js new file mode 100644 index 00000000000..cd3536e7a40 --- /dev/null +++ b/apps/server/static-assets/h5p/core/js/h5p-confirmation-dialog.js @@ -0,0 +1,410 @@ +/*global H5P*/ +H5P.ConfirmationDialog = (function (EventDispatcher) { + "use strict"; + + /** + * Create a confirmation dialog + * + * @param [options] Options for confirmation dialog + * @param [options.instance] Instance that uses confirmation dialog + * @param [options.headerText] Header text + * @param [options.dialogText] Dialog text + * @param [options.cancelText] Cancel dialog button text + * @param [options.confirmText] Confirm dialog button text + * @param [options.hideCancel] Hide cancel button + * @param [options.hideExit] Hide exit button + * @param [options.skipRestoreFocus] Skip restoring focus when hiding the dialog + * @param [options.classes] Extra classes for popup + * @constructor + */ + function ConfirmationDialog(options) { + EventDispatcher.call(this); + var self = this; + + // Make sure confirmation dialogs have unique id + H5P.ConfirmationDialog.uniqueId += 1; + var uniqueId = H5P.ConfirmationDialog.uniqueId; + + // Default options + options = options || {}; + options.headerText = options.headerText || H5P.t('confirmDialogHeader'); + options.dialogText = options.dialogText || H5P.t('confirmDialogBody'); + options.cancelText = options.cancelText || H5P.t('cancelLabel'); + options.confirmText = options.confirmText || H5P.t('confirmLabel'); + + /** + * Handle confirming event + * @param {Event} e + */ + function dialogConfirmed(e) { + self.hide(); + self.trigger('confirmed'); + e.preventDefault(); + } + + /** + * Handle dialog canceled + * @param {Event} e + */ + function dialogCanceled(e) { + self.hide(); + self.trigger('canceled'); + e.preventDefault(); + } + + /** + * Flow focus to element + * @param {HTMLElement} element Next element to be focused + * @param {Event} e Original tab event + */ + function flowTo(element, e) { + element.focus(); + e.preventDefault(); + } + + // Offset of exit button + var exitButtonOffset = 2 * 16; + var shadowOffset = 8; + + // Determine if we are too large for our container and must resize + var resizeIFrame = false; + + // Create background + var popupBackground = document.createElement('div'); + popupBackground.classList + .add('h5p-confirmation-dialog-background', 'hidden', 'hiding'); + + // Create outer popup + var popup = document.createElement('div'); + popup.classList.add('h5p-confirmation-dialog-popup', 'hidden'); + if (options.classes) { + options.classes.forEach(function (popupClass) { + popup.classList.add(popupClass); + }); + } + + popup.setAttribute('role', 'dialog'); + popup.setAttribute('aria-labelledby', 'h5p-confirmation-dialog-dialog-text-' + uniqueId); + popupBackground.appendChild(popup); + popup.addEventListener('keydown', function (e) { + if (e.which === 27) {// Esc key + // Exit dialog + dialogCanceled(e); + } + }); + + // Popup header + var header = document.createElement('div'); + header.classList.add('h5p-confirmation-dialog-header'); + popup.appendChild(header); + + // Header text + var headerText = document.createElement('div'); + headerText.classList.add('h5p-confirmation-dialog-header-text'); + headerText.innerHTML = options.headerText; + header.appendChild(headerText); + + // Popup body + var body = document.createElement('div'); + body.classList.add('h5p-confirmation-dialog-body'); + popup.appendChild(body); + + // Popup text + var text = document.createElement('div'); + text.classList.add('h5p-confirmation-dialog-text'); + text.innerHTML = options.dialogText; + text.id = 'h5p-confirmation-dialog-dialog-text-' + uniqueId; + body.appendChild(text); + + // Popup buttons + var buttons = document.createElement('div'); + buttons.classList.add('h5p-confirmation-dialog-buttons'); + body.appendChild(buttons); + + // Cancel button + var cancelButton = document.createElement('button'); + cancelButton.classList.add('h5p-core-cancel-button'); + cancelButton.textContent = options.cancelText; + + // Confirm button + var confirmButton = document.createElement('button'); + confirmButton.classList.add('h5p-core-button'); + confirmButton.classList.add('h5p-confirmation-dialog-confirm-button'); + confirmButton.textContent = options.confirmText; + + // Exit button + var exitButton = document.createElement('button'); + exitButton.classList.add('h5p-confirmation-dialog-exit'); + exitButton.setAttribute('aria-hidden', 'true'); + exitButton.tabIndex = -1; + exitButton.title = options.cancelText; + + // Cancel handler + cancelButton.addEventListener('click', dialogCanceled); + cancelButton.addEventListener('keydown', function (e) { + if (e.which === 32) { // Space + dialogCanceled(e); + } + else if (e.which === 9 && e.shiftKey) { // Shift-tab + flowTo(confirmButton, e); + } + }); + + if (!options.hideCancel) { + buttons.appendChild(cancelButton); + } + else { + // Center buttons + buttons.classList.add('center'); + } + + // Confirm handler + confirmButton.addEventListener('click', dialogConfirmed); + confirmButton.addEventListener('keydown', function (e) { + if (e.which === 32) { // Space + dialogConfirmed(e); + } + else if (e.which === 9 && !e.shiftKey) { // Tab + const nextButton = !options.hideCancel ? cancelButton : confirmButton; + flowTo(nextButton, e); + } + }); + buttons.appendChild(confirmButton); + + // Exit handler + exitButton.addEventListener('click', dialogCanceled); + exitButton.addEventListener('keydown', function (e) { + if (e.which === 32) { // Space + dialogCanceled(e); + } + }); + if (!options.hideExit) { + popup.appendChild(exitButton); + } + + // Wrapper element + var wrapperElement; + + // Focus capturing + var focusPredator; + + // Maintains hidden state of elements + var wrapperSiblingsHidden = []; + var popupSiblingsHidden = []; + + // Element with focus before dialog + var previouslyFocused; + + /** + * Set parent of confirmation dialog + * @param {HTMLElement} wrapper + * @returns {H5P.ConfirmationDialog} + */ + this.appendTo = function (wrapper) { + wrapperElement = wrapper; + return this; + }; + + /** + * Capture the focus element, send it to confirmation button + * @param {Event} e Original focus event + */ + var captureFocus = function (e) { + if (!popupBackground.contains(e.target)) { + e.preventDefault(); + confirmButton.focus(); + } + }; + + /** + * Hide siblings of element from assistive technology + * + * @param {HTMLElement} element + * @returns {Array} The previous hidden state of all siblings + */ + var hideSiblings = function (element) { + var hiddenSiblings = []; + var siblings = element.parentNode.children; + var i; + for (i = 0; i < siblings.length; i += 1) { + // Preserve hidden state + hiddenSiblings[i] = siblings[i].getAttribute('aria-hidden') ? + true : false; + + if (siblings[i] !== element) { + siblings[i].setAttribute('aria-hidden', true); + } + } + return hiddenSiblings; + }; + + /** + * Restores assistive technology state of element's siblings + * + * @param {HTMLElement} element + * @param {Array} hiddenSiblings Hidden state of all siblings + */ + var restoreSiblings = function (element, hiddenSiblings) { + var siblings = element.parentNode.children; + var i; + for (i = 0; i < siblings.length; i += 1) { + if (siblings[i] !== element && !hiddenSiblings[i]) { + siblings[i].removeAttribute('aria-hidden'); + } + } + }; + + /** + * Start capturing focus of parent and send it to dialog + */ + var startCapturingFocus = function () { + focusPredator = wrapperElement.parentNode || wrapperElement; + focusPredator.addEventListener('focus', captureFocus, true); + }; + + /** + * Clean up event listener for capturing focus + */ + var stopCapturingFocus = function () { + focusPredator.removeAttribute('aria-hidden'); + focusPredator.removeEventListener('focus', captureFocus, true); + }; + + /** + * Hide siblings in underlay from assistive technologies + */ + var disableUnderlay = function () { + wrapperSiblingsHidden = hideSiblings(wrapperElement); + popupSiblingsHidden = hideSiblings(popupBackground); + }; + + /** + * Restore state of underlay for assistive technologies + */ + var restoreUnderlay = function () { + restoreSiblings(wrapperElement, wrapperSiblingsHidden); + restoreSiblings(popupBackground, popupSiblingsHidden); + }; + + /** + * Fit popup to container. Makes sure it doesn't overflow. + * @params {number} [offsetTop] Offset of popup + */ + var fitToContainer = function (offsetTop) { + var popupOffsetTop = parseInt(popup.style.top, 10); + if (offsetTop !== undefined) { + popupOffsetTop = offsetTop; + } + + if (!popupOffsetTop) { + popupOffsetTop = 0; + } + + // Overflows height + if (popupOffsetTop + popup.offsetHeight > wrapperElement.offsetHeight) { + popupOffsetTop = wrapperElement.offsetHeight - popup.offsetHeight - shadowOffset; + } + + if (popupOffsetTop - exitButtonOffset <= 0) { + popupOffsetTop = exitButtonOffset + shadowOffset; + + // We are too big and must resize + resizeIFrame = true; + } + popup.style.top = popupOffsetTop + 'px'; + }; + + /** + * Show confirmation dialog + * @params {number} offsetTop Offset top + * @returns {H5P.ConfirmationDialog} + */ + this.show = function (offsetTop) { + // Capture focused item + previouslyFocused = document.activeElement; + wrapperElement.appendChild(popupBackground); + startCapturingFocus(); + disableUnderlay(); + popupBackground.classList.remove('hidden'); + fitToContainer(offsetTop); + setTimeout(function () { + popup.classList.remove('hidden'); + popupBackground.classList.remove('hiding'); + + setTimeout(function () { + // Focus confirm button + confirmButton.focus(); + + // Resize iFrame if necessary + if (resizeIFrame && options.instance) { + var minHeight = parseInt(popup.offsetHeight, 10) + + exitButtonOffset + (2 * shadowOffset); + self.setViewPortMinimumHeight(minHeight); + options.instance.trigger('resize'); + resizeIFrame = false; + } + }, 100); + }, 0); + + return this; + }; + + /** + * Hide confirmation dialog + * @returns {H5P.ConfirmationDialog} + */ + this.hide = function () { + popupBackground.classList.add('hiding'); + popup.classList.add('hidden'); + + // Restore focus + stopCapturingFocus(); + if (!options.skipRestoreFocus) { + previouslyFocused.focus(); + } + restoreUnderlay(); + setTimeout(function () { + popupBackground.classList.add('hidden'); + wrapperElement.removeChild(popupBackground); + self.setViewPortMinimumHeight(null); + }, 100); + + return this; + }; + + /** + * Retrieve element + * + * @return {HTMLElement} + */ + this.getElement = function () { + return popup; + }; + + /** + * Get previously focused element + * @return {HTMLElement} + */ + this.getPreviouslyFocused = function () { + return previouslyFocused; + }; + + /** + * Sets the minimum height of the view port + * + * @param {number|null} minHeight + */ + this.setViewPortMinimumHeight = function (minHeight) { + var container = document.querySelector('.h5p-container') || document.body; + container.style.minHeight = (typeof minHeight === 'number') ? (minHeight + 'px') : minHeight; + }; + } + + ConfirmationDialog.prototype = Object.create(EventDispatcher.prototype); + ConfirmationDialog.prototype.constructor = ConfirmationDialog; + + return ConfirmationDialog; + +}(H5P.EventDispatcher)); + +H5P.ConfirmationDialog.uniqueId = -1; diff --git a/apps/server/static-assets/h5p/core/js/h5p-content-type.js b/apps/server/static-assets/h5p/core/js/h5p-content-type.js new file mode 100644 index 00000000000..47c4d21bf75 --- /dev/null +++ b/apps/server/static-assets/h5p/core/js/h5p-content-type.js @@ -0,0 +1,41 @@ +/** + * H5P.ContentType is a base class for all content types. Used by newRunnable() + * + * Functions here may be overridable by the libraries. In special cases, + * it is also possible to override H5P.ContentType on a global level. + * + * NOTE that this doesn't actually 'extend' the event dispatcher but instead + * it creates a single instance which all content types shares as their base + * prototype. (in some cases this may be the root of strange event behavior) + * + * @class + * @augments H5P.EventDispatcher + */ +H5P.ContentType = function (isRootLibrary) { + + function ContentType() {} + + // Inherit from EventDispatcher. + ContentType.prototype = new H5P.EventDispatcher(); + + /** + * Is library standalone or not? Not beeing standalone, means it is + * included in another library + * + * @return {Boolean} + */ + ContentType.prototype.isRoot = function () { + return isRootLibrary; + }; + + /** + * Returns the file path of a file in the current library + * @param {string} filePath The path to the file relative to the library folder + * @return {string} The full path to the file + */ + ContentType.prototype.getLibraryFilePath = function (filePath) { + return H5P.getLibraryPath(this.libraryInfo.versionedNameNoSpaces) + '/' + filePath; + }; + + return ContentType; +}; diff --git a/apps/server/static-assets/h5p/core/js/h5p-content-upgrade-process.js b/apps/server/static-assets/h5p/core/js/h5p-content-upgrade-process.js new file mode 100644 index 00000000000..fbaa4f2bf07 --- /dev/null +++ b/apps/server/static-assets/h5p/core/js/h5p-content-upgrade-process.js @@ -0,0 +1,313 @@ +/*jshint -W083 */ +var H5PUpgrades = H5PUpgrades || {}; + +H5P.ContentUpgradeProcess = (function (Version) { + + /** + * @class + * @namespace H5P + */ + function ContentUpgradeProcess(name, oldVersion, newVersion, params, id, loadLibrary, done) { + var self = this; + + // Make params possible to work with + try { + params = JSON.parse(params); + if (!(params instanceof Object)) { + throw true; + } + } + catch (event) { + return done({ + type: 'errorParamsBroken', + id: id + }); + } + + self.loadLibrary = loadLibrary; + self.upgrade(name, oldVersion, newVersion, params.params, params.metadata, function (err, upgradedParams, upgradedMetadata) { + if (err) { + err.id = id; + return done(err); + } + + done(null, JSON.stringify({params: upgradedParams, metadata: upgradedMetadata})); + }); + } + + /** + * Run content upgrade. + * + * @public + * @param {string} name + * @param {Version} oldVersion + * @param {Version} newVersion + * @param {Object} params + * @param {Object} metadata + * @param {Function} done + */ + ContentUpgradeProcess.prototype.upgrade = function (name, oldVersion, newVersion, params, metadata, done) { + var self = this; + + // Load library details and upgrade routines + self.loadLibrary(name, newVersion, function (err, library) { + if (err) { + return done(err); + } + if (library.semantics === null) { + return done({ + type: 'libraryMissing', + library: library.name + ' ' + library.version.major + '.' + library.version.minor + }); + } + + // Run upgrade routines on params + self.processParams(library, oldVersion, newVersion, params, metadata, function (err, params, metadata) { + if (err) { + return done(err); + } + + // Check if any of the sub-libraries need upgrading + asyncSerial(library.semantics, function (index, field, next) { + self.processField(field, params[field.name], function (err, upgradedParams) { + if (upgradedParams) { + params[field.name] = upgradedParams; + } + next(err); + }); + }, function (err) { + done(err, params, metadata); + }); + }); + }); + }; + + /** + * Run upgrade hooks on params. + * + * @public + * @param {Object} library + * @param {Version} oldVersion + * @param {Version} newVersion + * @param {Object} params + * @param {Function} next + */ + ContentUpgradeProcess.prototype.processParams = function (library, oldVersion, newVersion, params, metadata, next) { + if (H5PUpgrades[library.name] === undefined) { + if (library.upgradesScript) { + // Upgrades script should be loaded so the upgrades should be here. + return next({ + type: 'scriptMissing', + library: library.name + ' ' + newVersion + }); + } + + // No upgrades script. Move on + return next(null, params, metadata); + } + + // Run upgrade hooks. Start by going through major versions + asyncSerial(H5PUpgrades[library.name], function (major, minors, nextMajor) { + if (major < oldVersion.major || major > newVersion.major) { + // Older than the current version or newer than the selected + nextMajor(); + } + else { + // Go through the minor versions for this major version + asyncSerial(minors, function (minor, upgrade, nextMinor) { + minor =+ minor; + if (minor <= oldVersion.minor || minor > newVersion.minor) { + // Older than or equal to the current version or newer than the selected + nextMinor(); + } + else { + // We found an upgrade hook, run it + var unnecessaryWrapper = (upgrade.contentUpgrade !== undefined ? upgrade.contentUpgrade : upgrade); + + try { + unnecessaryWrapper(params, function (err, upgradedParams, upgradedExtras) { + params = upgradedParams; + if (upgradedExtras && upgradedExtras.metadata) { // Optional + metadata = upgradedExtras.metadata; + } + nextMinor(err); + }, {metadata: metadata}); + } + catch (err) { + if (console && console.error) { + console.error("Error", err.stack); + console.error("Error", err.name); + console.error("Error", err.message); + } + next(err); + } + } + }, nextMajor); + } + }, function (err) { + next(err, params, metadata); + }); + }; + + /** + * Process parameter fields to find and upgrade sub-libraries. + * + * @public + * @param {Object} field + * @param {Object} params + * @param {Function} done + */ + ContentUpgradeProcess.prototype.processField = function (field, params, done) { + var self = this; + + if (params === undefined) { + return done(); + } + + switch (field.type) { + case 'library': + if (params.library === undefined || params.params === undefined) { + return done(); + } + + // Look for available upgrades + var usedLib = params.library.split(' ', 2); + for (var i = 0; i < field.options.length; i++) { + var availableLib = (typeof field.options[i] === 'string') ? field.options[i].split(' ', 2) : field.options[i].name.split(' ', 2); + if (availableLib[0] === usedLib[0]) { + if (availableLib[1] === usedLib[1]) { + return done(); // Same version + } + + // We have different versions + var usedVer = new Version(usedLib[1]); + var availableVer = new Version(availableLib[1]); + if (usedVer.major > availableVer.major || (usedVer.major === availableVer.major && usedVer.minor >= availableVer.minor)) { + return done({ + type: 'errorTooHighVersion', + used: usedLib[0] + ' ' + usedVer, + supported: availableLib[0] + ' ' + availableVer + }); // Larger or same version that's available + } + + // A newer version is available, upgrade params + return self.upgrade(availableLib[0], usedVer, availableVer, params.params, params.metadata, function (err, upgradedParams, upgradedMetadata) { + if (!err) { + params.library = availableLib[0] + ' ' + availableVer.major + '.' + availableVer.minor; + params.params = upgradedParams; + if (upgradedMetadata) { + params.metadata = upgradedMetadata; + } + } + done(err, params); + }); + } + } + + // Content type was not supporte by the higher version + done({ + type: 'errorNotSupported', + used: usedLib[0] + ' ' + usedVer + }); + break; + + case 'group': + if (field.fields.length === 1 && field.isSubContent !== true) { + // Single field to process, wrapper will be skipped + self.processField(field.fields[0], params, function (err, upgradedParams) { + if (upgradedParams) { + params = upgradedParams; + } + done(err, params); + }); + } + else { + // Go through all fields in the group + asyncSerial(field.fields, function (index, subField, next) { + var paramsToProcess = params ? params[subField.name] : null; + self.processField(subField, paramsToProcess, function (err, upgradedParams) { + if (upgradedParams) { + params[subField.name] = upgradedParams; + } + next(err); + }); + + }, function (err) { + done(err, params); + }); + } + break; + + case 'list': + // Go trough all params in the list + asyncSerial(params, function (index, subParams, next) { + self.processField(field.field, subParams, function (err, upgradedParams) { + if (upgradedParams) { + params[index] = upgradedParams; + } + next(err); + }); + }, function (err) { + done(err, params); + }); + break; + + default: + done(); + } + }; + + /** + * Helps process each property on the given object asynchronously in serial order. + * + * @private + * @param {Object} obj + * @param {Function} process + * @param {Function} finished + */ + var asyncSerial = function (obj, process, finished) { + var id, isArray = obj instanceof Array; + + // Keep track of each property that belongs to this object. + if (!isArray) { + var ids = []; + for (id in obj) { + if (obj.hasOwnProperty(id)) { + ids.push(id); + } + } + } + + var i = -1; // Keeps track of the current property + + /** + * Private. Process the next property + */ + var next = function () { + id = isArray ? i : ids[i]; + process(id, obj[id], check); + }; + + /** + * Private. Check if we're done or have an error. + * + * @param {String} err + */ + var check = function (err) { + // We need to use a real async function in order for the stack to clear. + setTimeout(function () { + i++; + if (i === (isArray ? obj.length : ids.length) || (err !== undefined && err !== null)) { + finished(err); + } + else { + next(); + } + }, 0); + }; + + check(); // Start + }; + + return ContentUpgradeProcess; +})(H5P.Version); diff --git a/apps/server/static-assets/h5p/core/js/h5p-content-upgrade-worker.js b/apps/server/static-assets/h5p/core/js/h5p-content-upgrade-worker.js new file mode 100644 index 00000000000..3507a358a1a --- /dev/null +++ b/apps/server/static-assets/h5p/core/js/h5p-content-upgrade-worker.js @@ -0,0 +1,63 @@ +/* global importScripts */ +var H5P = H5P || {}; +importScripts('h5p-version.js', 'h5p-content-upgrade-process.js'); + +var libraryLoadedCallback; + +/** + * Register message handlers + */ +var messageHandlers = { + newJob: function (job) { + // Start new job + new H5P.ContentUpgradeProcess(job.name, new H5P.Version(job.oldVersion), new H5P.Version(job.newVersion), job.params, job.id, function loadLibrary(name, version, next) { + // TODO: Cache? + postMessage({ + action: 'loadLibrary', + name: name, + version: version.toString() + }); + libraryLoadedCallback = next; + }, function done(err, result) { + if (err) { + // Return error + postMessage({ + action: 'error', + id: job.id, + err: err.message ? err.message : err + }); + + return; + } + + // Return upgraded content + postMessage({ + action: 'done', + id: job.id, + params: result + }); + }); + }, + libraryLoaded: function (data) { + var library = data.library; + if (library.upgradesScript) { + try { + importScripts(library.upgradesScript); + } + catch (err) { + libraryLoadedCallback(err); + return; + } + } + libraryLoadedCallback(null, data.library); + } +}; + +/** + * Handle messages from our master + */ +onmessage = function (event) { + if (event.data.action !== undefined && messageHandlers[event.data.action]) { + messageHandlers[event.data.action].call(this, event.data); + } +}; diff --git a/apps/server/static-assets/h5p/core/js/h5p-content-upgrade.js b/apps/server/static-assets/h5p/core/js/h5p-content-upgrade.js new file mode 100644 index 00000000000..9dc066c5c25 --- /dev/null +++ b/apps/server/static-assets/h5p/core/js/h5p-content-upgrade.js @@ -0,0 +1,445 @@ +/* global H5PAdminIntegration H5PUtils */ + +(function ($, Version) { + var info, $log, $container, librariesCache = {}, scriptsCache = {}; + + // Initialize + $(document).ready(function () { + // Get library info + info = H5PAdminIntegration.libraryInfo; + + // Get and reset container + const $wrapper = $('#h5p-admin-container').html(''); + $log = $('
      ').appendTo($wrapper); + $container = $('

      ' + info.message + '

      ').appendTo($wrapper); + + // Make it possible to select version + var $version = $(getVersionSelect(info.versions)).appendTo($container); + + // Add "go" button + $(''); + H5PLibraryDetails.$next = $(''); + + H5PLibraryDetails.$previous.on('click', function () { + if (H5PLibraryDetails.$previous.hasClass('disabled')) { + return; + } + + H5PLibraryDetails.currentPage--; + H5PLibraryDetails.updatePager(); + H5PLibraryDetails.createContentTable(); + }); + + H5PLibraryDetails.$next.on('click', function () { + if (H5PLibraryDetails.$next.hasClass('disabled')) { + return; + } + + H5PLibraryDetails.currentPage++; + H5PLibraryDetails.updatePager(); + H5PLibraryDetails.createContentTable(); + }); + + // This is the Page x of y widget: + H5PLibraryDetails.$pagerInfo = $(''); + + H5PLibraryDetails.$pager = $('
      ').append(H5PLibraryDetails.$previous, H5PLibraryDetails.$pagerInfo, H5PLibraryDetails.$next); + H5PLibraryDetails.$content.append(H5PLibraryDetails.$pager); + + H5PLibraryDetails.$pagerInfo.on('click', function () { + var width = H5PLibraryDetails.$pagerInfo.innerWidth(); + H5PLibraryDetails.$pagerInfo.hide(); + + // User has updated the pageNumber + var pageNumerUpdated = function () { + var newPageNum = $gotoInput.val()-1; + var intRegex = /^\d+$/; + + $goto.remove(); + H5PLibraryDetails.$pagerInfo.css({display: 'inline-block'}); + + // Check if input value is valid, and that it has actually changed + if (!(intRegex.test(newPageNum) && newPageNum >= 0 && newPageNum < H5PLibraryDetails.getNumPages() && newPageNum != H5PLibraryDetails.currentPage)) { + return; + } + + H5PLibraryDetails.currentPage = newPageNum; + H5PLibraryDetails.updatePager(); + H5PLibraryDetails.createContentTable(); + }; + + // We create an input box where the user may type in the page number + // he wants to be displayed. + // Reson for doing this is when user has ten-thousands of elements in list, + // this is the easiest way of getting to a specified page + var $gotoInput = $('', { + type: 'number', + min : 1, + max: H5PLibraryDetails.getNumPages(), + on: { + // Listen to blur, and the enter-key: + 'blur': pageNumerUpdated, + 'keyup': function (event) { + if (event.keyCode === 13) { + pageNumerUpdated(); + } + } + } + }).css({width: width}); + var $goto = $('', { + 'class': 'h5p-pager-goto' + }).css({width: width}).append($gotoInput).insertAfter(H5PLibraryDetails.$pagerInfo); + + $gotoInput.focus(); + }); + + H5PLibraryDetails.updatePager(); + }; + + /** + * Calculates number of pages + */ + H5PLibraryDetails.getNumPages = function () { + return Math.ceil(H5PLibraryDetails.currentContent.length / H5PLibraryDetails.PAGER_SIZE); + }; + + /** + * Update the pager text, and enables/disables the next and previous buttons as needed + */ + H5PLibraryDetails.updatePager = function () { + H5PLibraryDetails.$pagerInfo.css({display: 'inline-block'}); + + if (H5PLibraryDetails.getNumPages() > 0) { + var message = H5PUtils.translateReplace(H5PLibraryDetails.library.translations.pageXOfY, { + '$x': (H5PLibraryDetails.currentPage+1), + '$y': H5PLibraryDetails.getNumPages() + }); + H5PLibraryDetails.$pagerInfo.html(message); + } + else { + H5PLibraryDetails.$pagerInfo.html(''); + } + + H5PLibraryDetails.$previous.toggleClass('disabled', H5PLibraryDetails.currentPage <= 0); + H5PLibraryDetails.$next.toggleClass('disabled', H5PLibraryDetails.currentContent.length < (H5PLibraryDetails.currentPage+1)*H5PLibraryDetails.PAGER_SIZE); + }; + + /** + * Creates the search element + */ + H5PLibraryDetails.createSearchElement = function () { + + H5PLibraryDetails.$search = $(''); + + var performSeach = function () { + var searchString = $('.h5p-content-search > input').val(); + + // If search string same as previous, just do nothing + if (H5PLibraryDetails.currentFilter === searchString) { + return; + } + + if (searchString.trim().length === 0) { + // If empty search, use the complete list + H5PLibraryDetails.currentContent = H5PLibraryDetails.library.content; + } + else if (H5PLibraryDetails.filterCache[searchString]) { + // If search is cached, no need to filter + H5PLibraryDetails.currentContent = H5PLibraryDetails.filterCache[searchString]; + } + else { + var listToFilter = H5PLibraryDetails.library.content; + + // Check if we can filter the already filtered results (for performance) + if (searchString.length > 1 && H5PLibraryDetails.currentFilter === searchString.substr(0, H5PLibraryDetails.currentFilter.length)) { + listToFilter = H5PLibraryDetails.currentContent; + } + H5PLibraryDetails.currentContent = $.grep(listToFilter, function (content) { + return content.title && content.title.match(new RegExp(searchString, 'i')); + }); + } + + H5PLibraryDetails.currentFilter = searchString; + // Cache the current result + H5PLibraryDetails.filterCache[searchString] = H5PLibraryDetails.currentContent; + H5PLibraryDetails.currentPage = 0; + H5PLibraryDetails.createContentTable(); + + // Display search results: + if (H5PLibraryDetails.$searchResults) { + H5PLibraryDetails.$searchResults.remove(); + } + if (searchString.trim().length > 0) { + H5PLibraryDetails.$searchResults = $('' + H5PLibraryDetails.currentContent.length + ' hits on ' + H5PLibraryDetails.currentFilter + ''); + H5PLibraryDetails.$search.append(H5PLibraryDetails.$searchResults); + } + H5PLibraryDetails.updatePager(); + }; + + var inputTimer; + $('input', H5PLibraryDetails.$search).on('change keypress paste input', function () { + // Here we start the filtering + // We wait at least 500 ms after last input to perform search + if (inputTimer) { + clearTimeout(inputTimer); + } + + inputTimer = setTimeout( function () { + performSeach(); + }, 500); + }); + + H5PLibraryDetails.$content.append(H5PLibraryDetails.$search); + }; + + /** + * Creates the page size selector + */ + H5PLibraryDetails.createPageSizeSelector = function () { + H5PLibraryDetails.$search.append('
      ' + H5PLibraryDetails.library.translations.pageSizeSelectorLabel + ':102050100200
      '); + + // Listen to clicks on the page size selector: + $('.h5p-admin-pager-size-selector > span', H5PLibraryDetails.$search).on('click', function () { + H5PLibraryDetails.PAGER_SIZE = $(this).data('page-size'); + $('.h5p-admin-pager-size-selector > span', H5PLibraryDetails.$search).removeClass('selected'); + $(this).addClass('selected'); + H5PLibraryDetails.currentPage = 0; + H5PLibraryDetails.createContentTable(); + H5PLibraryDetails.updatePager(); + }); + }; + + // Initialize me: + $(document).ready(function () { + if (!H5PLibraryDetails.initialized) { + H5PLibraryDetails.initialized = true; + H5PLibraryDetails.init(); + } + }); + +})(H5P.jQuery); diff --git a/apps/server/static-assets/h5p/core/js/h5p-library-list.js b/apps/server/static-assets/h5p/core/js/h5p-library-list.js new file mode 100644 index 00000000000..344b7367234 --- /dev/null +++ b/apps/server/static-assets/h5p/core/js/h5p-library-list.js @@ -0,0 +1,140 @@ +/* global H5PAdminIntegration H5PUtils */ +var H5PLibraryList = H5PLibraryList || {}; + +(function ($) { + + /** + * Initializing + */ + H5PLibraryList.init = function () { + var $adminContainer = H5P.jQuery(H5PAdminIntegration.containerSelector).html(''); + + var libraryList = H5PAdminIntegration.libraryList; + if (libraryList.notCached) { + $adminContainer.append(H5PUtils.getRebuildCache(libraryList.notCached)); + } + + // Create library list + $adminContainer.append(H5PLibraryList.createLibraryList(H5PAdminIntegration.libraryList)); + }; + + /** + * Create the library list + * + * @param {object} libraries List of libraries and headers + */ + H5PLibraryList.createLibraryList = function (libraries) { + var t = H5PAdminIntegration.l10n; + if (libraries.listData === undefined || libraries.listData.length === 0) { + return $('
      ' + t.NA + '
      '); + } + + // Create table + var $table = H5PUtils.createTable(libraries.listHeaders); + $table.addClass('libraries'); + + // Add libraries + $.each (libraries.listData, function (index, library) { + var $libraryRow = H5PUtils.createTableRow([ + library.title, + '', + { + text: library.numContent, + class: 'h5p-admin-center' + }, + { + text: library.numContentDependencies, + class: 'h5p-admin-center' + }, + { + text: library.numLibraryDependencies, + class: 'h5p-admin-center' + }, + '
      ' + + '' + + (library.detailsUrl ? '' : '') + + (library.deleteUrl ? '' : '') + + '
      ' + ]); + + H5PLibraryList.addRestricted($('.h5p-admin-restricted', $libraryRow), library.restrictedUrl, library.restricted); + + var hasContent = !(library.numContent === '' || library.numContent === 0); + if (library.upgradeUrl === null) { + $('.h5p-admin-upgrade-library', $libraryRow).remove(); + } + else if (library.upgradeUrl === false || !hasContent) { + $('.h5p-admin-upgrade-library', $libraryRow).attr('disabled', true); + } + else { + $('.h5p-admin-upgrade-library', $libraryRow).attr('title', t.upgradeLibrary).click(function () { + window.location.href = library.upgradeUrl; + }); + } + + // Open details view when clicked + $('.h5p-admin-view-library', $libraryRow).on('click', function () { + window.location.href = library.detailsUrl; + }); + + var $deleteButton = $('.h5p-admin-delete-library', $libraryRow); + if (libraries.notCached !== undefined || + hasContent || + (library.numContentDependencies !== '' && + library.numContentDependencies !== 0) || + (library.numLibraryDependencies !== '' && + library.numLibraryDependencies !== 0)) { + // Disabled delete if content. + $deleteButton.attr('disabled', true); + } + else { + // Go to delete page om click. + $deleteButton.attr('title', t.deleteLibrary).on('click', function () { + window.location.href = library.deleteUrl; + }); + } + + $table.append($libraryRow); + }); + + return $table; + }; + + H5PLibraryList.addRestricted = function ($checkbox, url, selected) { + if (selected === null) { + $checkbox.remove(); + } + else { + $checkbox.change(function () { + $checkbox.attr('disabled', true); + + $.ajax({ + dataType: 'json', + url: url, + cache: false + }).fail(function () { + $checkbox.attr('disabled', false); + + // Reset + $checkbox.attr('checked', !$checkbox.is(':checked')); + }).done(function (result) { + url = result.url; + $checkbox.attr('disabled', false); + }); + }); + + if (selected) { + $checkbox.attr('checked', true); + } + } + }; + + // Initialize me: + $(document).ready(function () { + if (!H5PLibraryList.initialized) { + H5PLibraryList.initialized = true; + H5PLibraryList.init(); + } + }); + +})(H5P.jQuery); diff --git a/apps/server/static-assets/h5p/core/js/h5p-resizer.js b/apps/server/static-assets/h5p/core/js/h5p-resizer.js new file mode 100644 index 00000000000..ed78724ec1a --- /dev/null +++ b/apps/server/static-assets/h5p/core/js/h5p-resizer.js @@ -0,0 +1,131 @@ +// H5P iframe Resizer +(function () { + if (!window.postMessage || !window.addEventListener || window.h5pResizerInitialized) { + return; // Not supported + } + window.h5pResizerInitialized = true; + + // Map actions to handlers + var actionHandlers = {}; + + /** + * Prepare iframe resize. + * + * @private + * @param {Object} iframe Element + * @param {Object} data Payload + * @param {Function} respond Send a response to the iframe + */ + actionHandlers.hello = function (iframe, data, respond) { + // Make iframe responsive + iframe.style.width = '100%'; + + // Bugfix for Chrome: Force update of iframe width. If this is not done the + // document size may not be updated before the content resizes. + iframe.getBoundingClientRect(); + + // Tell iframe that it needs to resize when our window resizes + var resize = function () { + if (iframe.contentWindow) { + // Limit resize calls to avoid flickering + respond('resize'); + } + else { + // Frame is gone, unregister. + window.removeEventListener('resize', resize); + } + }; + window.addEventListener('resize', resize, false); + + // Respond to let the iframe know we can resize it + respond('hello'); + }; + + /** + * Prepare iframe resize. + * + * @private + * @param {Object} iframe Element + * @param {Object} data Payload + * @param {Function} respond Send a response to the iframe + */ + actionHandlers.prepareResize = function (iframe, data, respond) { + // Do not resize unless page and scrolling differs + if (iframe.clientHeight !== data.scrollHeight || + data.scrollHeight !== data.clientHeight) { + + // Reset iframe height, in case content has shrinked. + iframe.style.height = data.clientHeight + 'px'; + respond('resizePrepared'); + } + }; + + /** + * Resize parent and iframe to desired height. + * + * @private + * @param {Object} iframe Element + * @param {Object} data Payload + * @param {Function} respond Send a response to the iframe + */ + actionHandlers.resize = function (iframe, data) { + // Resize iframe so all content is visible. Use scrollHeight to make sure we get everything + iframe.style.height = data.scrollHeight + 'px'; + }; + + /** + * Keyup event handler. Exits full screen on escape. + * + * @param {Event} event + */ + var escape = function (event) { + if (event.keyCode === 27) { + exitFullScreen(); + } + }; + + // Listen for messages from iframes + window.addEventListener('message', function receiveMessage(event) { + if (event.data.context !== 'h5p') { + return; // Only handle h5p requests. + } + + // Find out who sent the message + var iframe, iframes = document.getElementsByTagName('iframe'); + for (var i = 0; i < iframes.length; i++) { + if (iframes[i].contentWindow === event.source) { + iframe = iframes[i]; + break; + } + } + + if (!iframe) { + return; // Cannot find sender + } + + // Find action handler handler + if (actionHandlers[event.data.action]) { + actionHandlers[event.data.action](iframe, event.data, function respond(action, data) { + if (data === undefined) { + data = {}; + } + data.action = action; + data.context = 'h5p'; + event.source.postMessage(data, event.origin); + }); + } + }, false); + + // Let h5p iframes know we're ready! + var iframes = document.getElementsByTagName('iframe'); + var ready = { + context: 'h5p', + action: 'ready' + }; + for (var i = 0; i < iframes.length; i++) { + if (iframes[i].src.indexOf('h5p') !== -1) { + iframes[i].contentWindow.postMessage(ready, '*'); + } + } + +})(); diff --git a/apps/server/static-assets/h5p/core/js/h5p-utils.js b/apps/server/static-assets/h5p/core/js/h5p-utils.js new file mode 100644 index 00000000000..b5aa3334e0e --- /dev/null +++ b/apps/server/static-assets/h5p/core/js/h5p-utils.js @@ -0,0 +1,506 @@ +/* global H5PAdminIntegration*/ +var H5PUtils = H5PUtils || {}; + +(function ($) { + /** + * Generic function for creating a table including the headers + * + * @param {array} headers List of headers + */ + H5PUtils.createTable = function (headers) { + var $table = $('
      '); + + if (headers) { + var $thead = $(''); + var $tr = $(''); + + $.each(headers, function (index, value) { + if (!(value instanceof Object)) { + value = { + html: value + }; + } + + $('', value).appendTo($tr); + }); + + $table.append($thead.append($tr)); + } + + return $table; + }; + + /** + * Generic function for creating a table row + * + * @param {array} rows Value list. Object name is used as class name in + */ + H5PUtils.createTableRow = function (rows) { + var $tr = $(''); + + $.each(rows, function (index, value) { + if (!(value instanceof Object)) { + value = { + html: value + }; + } + + $('', value).appendTo($tr); + }); + + return $tr; + }; + + /** + * Generic function for creating a field containing label and value + * + * @param {string} label The label displayed in front of the value + * @param {string} value The value + */ + H5PUtils.createLabeledField = function (label, value) { + var $field = $('
      '); + + $field.append('
      ' + label + '
      '); + $field.append('
      ' + value + '
      '); + + return $field; + }; + + /** + * Replaces placeholder fields in translation strings + * + * @param {string} template The translation template string in the following format: "$name is a $sex" + * @param {array} replacors An js object with key and values. Eg: {'$name': 'Frode', '$sex': 'male'} + */ + H5PUtils.translateReplace = function (template, replacors) { + $.each(replacors, function (key, value) { + template = template.replace(new RegExp('\\'+key, 'g'), value); + }); + return template; + }; + + /** + * Get throbber with given text. + * + * @param {String} text + * @returns {$} + */ + H5PUtils.throbber = function (text) { + return $('
      ', { + class: 'h5p-throbber', + text: text + }); + }; + + /** + * Makes it possbile to rebuild all content caches from admin UI. + * @param {Object} notCached + * @returns {$} + */ + H5PUtils.getRebuildCache = function (notCached) { + var $container = $('

      ' + notCached.message + '

      ' + notCached.progress + '

      '); + var $button = $('').appendTo($container).click(function () { + var $spinner = $('
      ', {class: 'h5p-spinner'}).replaceAll($button); + var parts = ['|', '/', '-', '\\']; + var current = 0; + var spinning = setInterval(function () { + $spinner.text(parts[current]); + current++; + if (current === parts.length) current = 0; + }, 100); + + var $counter = $container.find('.progress'); + var build = function () { + $.post(notCached.url, function (left) { + if (left === '0') { + clearInterval(spinning); + $container.remove(); + location.reload(); + } + else { + var counter = $counter.text().split(' '); + counter[0] = left; + $counter.text(counter.join(' ')); + build(); + } + }); + }; + build(); + }); + + return $container; + }; + + /** + * Generic table class with useful helpers. + * + * @class + * @param {Object} classes + * Custom html classes to use on elements. + * e.g. {tableClass: 'fixed'}. + */ + H5PUtils.Table = function (classes) { + var numCols; + var sortByCol; + var $sortCol; + var sortCol; + var sortDir; + + // Create basic table + var tableOptions = {}; + if (classes.table !== undefined) { + tableOptions['class'] = classes.table; + } + var $table = $('', tableOptions); + var $thead = $('').appendTo($table); + var $tfoot = $('').appendTo($table); + var $tbody = $('').appendTo($table); + + /** + * Add columns to given table row. + * + * @private + * @param {jQuery} $tr Table row + * @param {(String|Object)} col Column properties + * @param {Number} id Used to seperate the columns + */ + var addCol = function ($tr, col, id) { + var options = { + on: {} + }; + + if (!(col instanceof Object)) { + options.text = col; + } + else { + if (col.text !== undefined) { + options.text = col.text; + } + if (col.class !== undefined) { + options.class = col.class; + } + + if (sortByCol !== undefined && col.sortable === true) { + // Make sortable + options.role = 'button'; + options.tabIndex = 0; + + // This is the first sortable column, use as default sort + if (sortCol === undefined) { + sortCol = id; + sortDir = 0; + } + + // This is the sort column + if (sortCol === id) { + options['class'] = 'h5p-sort'; + if (sortDir === 1) { + options['class'] += ' h5p-reverse'; + } + } + + options.on.click = function () { + sort($th, id); + }; + options.on.keypress = function (event) { + if ((event.charCode || event.keyCode) === 32) { // Space + sort($th, id); + } + }; + } + } + + // Append + var $th = $(''); + var $tr = $('').appendTo($newThead); + for (var i = 0; i < cols.length; i++) { + addCol($tr, cols[i], i); + } + + // Update DOM + $thead.replaceWith($newThead); + $thead = $newThead; + }; + + /** + * Set table rows. + * + * @public + * @param {Array} rows Table rows with cols: [[1,'hello',3],[2,'asd',6]] + */ + this.setRows = function (rows) { + var $newTbody = $(''); + + for (var i = 0; i < rows.length; i++) { + var $tr = $('').appendTo($newTbody); + + for (var j = 0; j < rows[i].length; j++) { + $(''); + var $tr = $('').appendTo($newTbody); + $(''); + var $tr = $('').appendTo($newTfoot); + $('\s*$/g,At={option:[1,""],legend:[1,"
      ","
      "],area:[1,"",""],param:[1,"",""],thead:[1,"
      ', options).appendTo($tr); + if (sortCol === id) { + $sortCol = $th; // Default sort column + } + }; + + /** + * Updates the UI when a column header has been clicked. + * Triggers sorting callback. + * + * @private + * @param {jQuery} $th Table header + * @param {Number} id Used to seperate the columns + */ + var sort = function ($th, id) { + if (id === sortCol) { + // Change sorting direction + if (sortDir === 0) { + sortDir = 1; + $th.addClass('h5p-reverse'); + } + else { + sortDir = 0; + $th.removeClass('h5p-reverse'); + } + } + else { + // Change sorting column + $sortCol.removeClass('h5p-sort').removeClass('h5p-reverse'); + $sortCol = $th.addClass('h5p-sort'); + sortCol = id; + sortDir = 0; + } + + sortByCol({ + by: sortCol, + dir: sortDir + }); + }; + + /** + * Set table headers. + * + * @public + * @param {Array} cols + * Table header data. Can be strings or objects with options like + * "text" and "sortable". E.g. + * [{text: 'Col 1', sortable: true}, 'Col 2', 'Col 3'] + * @param {Function} sort Callback which is runned when sorting changes + * @param {Object} [order] + */ + this.setHeaders = function (cols, sort, order) { + numCols = cols.length; + sortByCol = sort; + + if (order) { + sortCol = order.by; + sortDir = order.dir; + } + + // Create new head + var $newThead = $('
      ', { + html: rows[i][j] + }).appendTo($tr); + } + } + + $tbody.replaceWith($newTbody); + $tbody = $newTbody; + + return $tbody; + }; + + /** + * Set custom table body content. This can be a message or a throbber. + * Will cover all table columns. + * + * @public + * @param {jQuery} $content Custom content + */ + this.setBody = function ($content) { + var $newTbody = $('
      ', { + colspan: numCols + }).append($content).appendTo($tr); + $tbody.replaceWith($newTbody); + $tbody = $newTbody; + }; + + /** + * Set custom table foot content. This can be a pagination widget. + * Will cover all table columns. + * + * @public + * @param {jQuery} $content Custom content + */ + this.setFoot = function ($content) { + var $newTfoot = $('
      ', { + colspan: numCols + }).append($content).appendTo($tr); + $tfoot.replaceWith($newTfoot); + }; + + + /** + * Appends the table to the given container. + * + * @public + * @param {jQuery} $container + */ + this.appendTo = function ($container) { + $table.appendTo($container); + }; + }; + + /** + * Generic pagination class. Creates a useful pagination widget. + * + * @class + * @param {Number} num Total number of items to pagiate. + * @param {Number} limit Number of items to dispaly per page. + * @param {Function} goneTo + * Callback which is fired when the user wants to go to another page. + * @param {Object} l10n + * Localization / translations. e.g. + * { + * currentPage: 'Page $current of $total', + * nextPage: 'Next page', + * previousPage: 'Previous page' + * } + */ + H5PUtils.Pagination = function (num, limit, goneTo, l10n) { + var current = 0; + var pages = Math.ceil(num / limit); + + // Create components + + // Previous button + var $left = $(''; + } + if (contentData.displayOptions.export && contentData.displayOptions.copy) { + html += '
      or
      '; + } + if (contentData.displayOptions.copy) { + html += ''; + } + + const dialog = new H5P.Dialog('reuse', H5P.t('reuseContent'), html, $element); + + // Selecting embed code when dialog is opened + H5P.jQuery(dialog).on('dialog-opened', function (e, $dialog) { + H5P.jQuery('More Info').click(function (e) { + e.stopPropagation(); + }).appendTo($dialog.find('h2')); + $dialog.find('.h5p-download-button').click(function () { + window.location.href = contentData.exportUrl; + instance.triggerXAPI('downloaded'); + dialog.close(); + }); + $dialog.find('.h5p-copy-button').click(function () { + const item = new H5P.ClipboardItem(library); + item.contentId = contentId; + H5P.setClipboard(item); + instance.triggerXAPI('copied'); + dialog.close(); + H5P.attachToastTo( + H5P.jQuery('.h5p-content:first')[0], + H5P.t('contentCopied'), + { + position: { + horizontal: 'centered', + vertical: 'centered', + noOverflowX: true + } + } + ); + }); + H5P.trigger(instance, 'resize'); + }).on('dialog-closed', function () { + H5P.trigger(instance, 'resize'); + }); + + dialog.open(); +}; + +/** + * Display a dialog containing the embed code. + * + * @param {H5P.jQuery} $element + * Element to insert dialog after. + * @param {string} embedCode + * The embed code. + * @param {string} resizeCode + * The advanced resize code + * @param {Object} size + * The content's size. + * @param {number} size.width + * @param {number} size.height + */ +H5P.openEmbedDialog = function ($element, embedCode, resizeCode, size, instance) { + var fullEmbedCode = embedCode + resizeCode; + var dialog = new H5P.Dialog('embed', H5P.t('embed'), '' + H5P.t('size') + ': × px
      ' + H5P.t('showAdvanced') + '

      ' + H5P.t('advancedHelp') + '

      ', $element); + + // Selecting embed code when dialog is opened + H5P.jQuery(dialog).on('dialog-opened', function (event, $dialog) { + var $inner = $dialog.find('.h5p-inner'); + var $scroll = $inner.find('.h5p-scroll-content'); + var diff = $scroll.outerHeight() - $scroll.innerHeight(); + var positionInner = function () { + H5P.trigger(instance, 'resize'); + }; + + // Handle changing of width/height + var $w = $dialog.find('.h5p-embed-size:eq(0)'); + var $h = $dialog.find('.h5p-embed-size:eq(1)'); + var getNum = function ($e, d) { + var num = parseFloat($e.val()); + if (isNaN(num)) { + return d; + } + return Math.ceil(num); + }; + var updateEmbed = function () { + $dialog.find('.h5p-embed-code-container:first').val(fullEmbedCode.replace(':w', getNum($w, size.width)).replace(':h', getNum($h, size.height))); + }; + + $w.change(updateEmbed); + $h.change(updateEmbed); + updateEmbed(); + + // Select text and expand textareas + $dialog.find('.h5p-embed-code-container').each(function () { + H5P.jQuery(this).css('height', this.scrollHeight + 'px').focus(function () { + H5P.jQuery(this).select(); + }); + }); + $dialog.find('.h5p-embed-code-container').eq(0).select(); + positionInner(); + + // Expand advanced embed + var expand = function () { + var $expander = H5P.jQuery(this); + var $content = $expander.next(); + if ($content.is(':visible')) { + $expander.removeClass('h5p-open').text(H5P.t('showAdvanced')).attr('aria-expanded', 'true'); + $content.hide(); + } + else { + $expander.addClass('h5p-open').text(H5P.t('hideAdvanced')).attr('aria-expanded', 'false'); + $content.show(); + } + $dialog.find('.h5p-embed-code-container').each(function () { + H5P.jQuery(this).css('height', this.scrollHeight + 'px'); + }); + positionInner(); + }; + $dialog.find('.h5p-expander').click(expand).keypress(function (event) { + if (event.keyCode === 32) { + expand.apply(this); + return false; + } + }); + }).on('dialog-closed', function () { + H5P.trigger(instance, 'resize'); + }); + + dialog.open(); +}; + +/** + * Show a toast message. + * + * The reference element could be dom elements the toast should be attached to, + * or e.g. the document body for general toast messages. + * + * @param {DOM} element Reference element to show toast message for. + * @param {string} message Message to show. + * @param {object} [config] Configuration. + * @param {string} [config.style=h5p-toast] Style name for the tooltip. + * @param {number} [config.duration=3000] Toast message length in ms. + * @param {object} [config.position] Relative positioning of the toast. + * @param {string} [config.position.horizontal=centered] [before|left|centered|right|after]. + * @param {string} [config.position.vertical=below] [above|top|centered|bottom|below]. + * @param {number} [config.position.offsetHorizontal=0] Extra horizontal offset. + * @param {number} [config.position.offsetVertical=0] Extra vetical offset. + * @param {boolean} [config.position.noOverflowLeft=false] True to prevent overflow left. + * @param {boolean} [config.position.noOverflowRight=false] True to prevent overflow right. + * @param {boolean} [config.position.noOverflowTop=false] True to prevent overflow top. + * @param {boolean} [config.position.noOverflowBottom=false] True to prevent overflow bottom. + * @param {boolean} [config.position.noOverflowX=false] True to prevent overflow left and right. + * @param {boolean} [config.position.noOverflowY=false] True to prevent overflow top and bottom. + * @param {object} [config.position.overflowReference=document.body] DOM reference for overflow. + */ +H5P.attachToastTo = function (element, message, config) { + if (element === undefined || message === undefined) { + return; + } + + const eventPath = function (evt) { + var path = (evt.composedPath && evt.composedPath()) || evt.path; + var target = evt.target; + + if (path != null) { + // Safari doesn't include Window, but it should. + return (path.indexOf(window) < 0) ? path.concat(window) : path; + } + + if (target === window) { + return [window]; + } + + function getParents(node, memo) { + memo = memo || []; + var parentNode = node.parentNode; + + if (!parentNode) { + return memo; + } + else { + return getParents(parentNode, memo.concat(parentNode)); + } + } + + return [target].concat(getParents(target), window); + }; + + /** + * Handle click while toast is showing. + */ + const clickHandler = function (event) { + /* + * A common use case will be to attach toasts to buttons that are clicked. + * The click would remove the toast message instantly without this check. + * Children of the clicked element are also ignored. + */ + var path = eventPath(event); + if (path.indexOf(element) !== -1) { + return; + } + clearTimeout(timer); + removeToast(); + }; + + + + /** + * Remove the toast message. + */ + const removeToast = function () { + document.removeEventListener('click', clickHandler); + if (toast.parentNode) { + toast.parentNode.removeChild(toast); + } + }; + + /** + * Get absolute coordinates for the toast. + * + * @param {DOM} element Reference element to show toast message for. + * @param {DOM} toast Toast element. + * @param {object} [position={}] Relative positioning of the toast message. + * @param {string} [position.horizontal=centered] [before|left|centered|right|after]. + * @param {string} [position.vertical=below] [above|top|centered|bottom|below]. + * @param {number} [position.offsetHorizontal=0] Extra horizontal offset. + * @param {number} [position.offsetVertical=0] Extra vetical offset. + * @param {boolean} [position.noOverflowLeft=false] True to prevent overflow left. + * @param {boolean} [position.noOverflowRight=false] True to prevent overflow right. + * @param {boolean} [position.noOverflowTop=false] True to prevent overflow top. + * @param {boolean} [position.noOverflowBottom=false] True to prevent overflow bottom. + * @param {boolean} [position.noOverflowX=false] True to prevent overflow left and right. + * @param {boolean} [position.noOverflowY=false] True to prevent overflow top and bottom. + * @return {object} + */ + const getToastCoordinates = function (element, toast, position) { + position = position || {}; + position.offsetHorizontal = position.offsetHorizontal || 0; + position.offsetVertical = position.offsetVertical || 0; + + const toastRect = toast.getBoundingClientRect(); + const elementRect = element.getBoundingClientRect(); + + let left = 0; + let top = 0; + + // Compute horizontal position + switch (position.horizontal) { + case 'before': + left = elementRect.left - toastRect.width - position.offsetHorizontal; + break; + case 'after': + left = elementRect.left + elementRect.width + position.offsetHorizontal; + break; + case 'left': + left = elementRect.left + position.offsetHorizontal; + break; + case 'right': + left = elementRect.left + elementRect.width - toastRect.width - position.offsetHorizontal; + break; + case 'centered': + left = elementRect.left + elementRect.width / 2 - toastRect.width / 2 + position.offsetHorizontal; + break; + default: + left = elementRect.left + elementRect.width / 2 - toastRect.width / 2 + position.offsetHorizontal; + } + + // Compute vertical position + switch (position.vertical) { + case 'above': + top = elementRect.top - toastRect.height - position.offsetVertical; + break; + case 'below': + top = elementRect.top + elementRect.height + position.offsetVertical; + break; + case 'top': + top = elementRect.top + position.offsetVertical; + break; + case 'bottom': + top = elementRect.top + elementRect.height - toastRect.height - position.offsetVertical; + break; + case 'centered': + top = elementRect.top + elementRect.height / 2 - toastRect.height / 2 + position.offsetVertical; + break; + default: + top = elementRect.top + elementRect.height + position.offsetVertical; + } + + // Prevent overflow + const overflowElement = document.body; + const bounds = overflowElement.getBoundingClientRect(); + if ((position.noOverflowLeft || position.noOverflowX) && (left < bounds.x)) { + left = bounds.x; + } + if ((position.noOverflowRight || position.noOverflowX) && ((left + toastRect.width) > (bounds.x + bounds.width))) { + left = bounds.x + bounds.width - toastRect.width; + } + if ((position.noOverflowTop || position.noOverflowY) && (top < bounds.y)) { + top = bounds.y; + } + if ((position.noOverflowBottom || position.noOverflowY) && ((top + toastRect.height) > (bounds.y + bounds.height))) { + left = bounds.y + bounds.height - toastRect.height; + } + + return {left: left, top: top}; + }; + + // Sanitization + config = config || {}; + config.style = config.style || 'h5p-toast'; + config.duration = config.duration || 3000; + + // Build toast + const toast = document.createElement('div'); + toast.setAttribute('id', config.style); + toast.classList.add('h5p-toast-disabled'); + toast.classList.add(config.style); + + const msg = document.createElement('span'); + msg.innerHTML = message; + toast.appendChild(msg); + + document.body.appendChild(toast); + + // The message has to be set before getting the coordinates + const coordinates = getToastCoordinates(element, toast, config.position); + toast.style.left = Math.round(coordinates.left) + 'px'; + toast.style.top = Math.round(coordinates.top) + 'px'; + + toast.classList.remove('h5p-toast-disabled'); + const timer = setTimeout(removeToast, config.duration); + + // The toast can also be removed by clicking somewhere + document.addEventListener('click', clickHandler); +}; + +/** + * Copyrights for a H5P Content Library. + * + * @class + */ +H5P.ContentCopyrights = function () { + var label; + var media = []; + var content = []; + + /** + * Set label. + * + * @param {string} newLabel + */ + this.setLabel = function (newLabel) { + label = newLabel; + }; + + /** + * Add sub content. + * + * @param {H5P.MediaCopyright} newMedia + */ + this.addMedia = function (newMedia) { + if (newMedia !== undefined) { + media.push(newMedia); + } + }; + + /** + * Add sub content in front. + * + * @param {H5P.MediaCopyright} newMedia + */ + this.addMediaInFront = function (newMedia) { + if (newMedia !== undefined) { + media.unshift(newMedia); + } + }; + + /** + * Add sub content. + * + * @param {H5P.ContentCopyrights} newContent + */ + this.addContent = function (newContent) { + if (newContent !== undefined) { + content.push(newContent); + } + }; + + /** + * Print content copyright. + * + * @returns {string} HTML. + */ + this.toString = function () { + var html = ''; + + // Add media rights + for (var i = 0; i < media.length; i++) { + html += media[i]; + } + + // Add sub content rights + for (i = 0; i < content.length; i++) { + html += content[i]; + } + + + if (html !== '') { + // Add a label to this info + if (label !== undefined) { + html = '

      ' + label + '

      ' + html; + } + + // Add wrapper + html = '
      ' + html + '
      '; + } + + return html; + }; +}; + +/** + * A ordered list of copyright fields for media. + * + * @class + * @param {Object} copyright + * Copyright information fields. + * @param {Object} [labels] + * Translation of labels. + * @param {Array} [order] + * Order of the fields. + * @param {Object} [extraFields] + * Add extra copyright fields. + */ +H5P.MediaCopyright = function (copyright, labels, order, extraFields) { + var thumbnail; + var list = new H5P.DefinitionList(); + + /** + * Get translated label for field. + * + * @private + * @param {string} fieldName + * @returns {string} + */ + var getLabel = function (fieldName) { + if (labels === undefined || labels[fieldName] === undefined) { + return H5P.t(fieldName); + } + + return labels[fieldName]; + }; + + /** + * Get humanized value for the license field. + * + * @private + * @param {string} license + * @param {string} [version] + * @returns {string} + */ + var humanizeLicense = function (license, version) { + var copyrightLicense = H5P.copyrightLicenses[license]; + + // Build license string + var value = ''; + if (!(license === 'PD' && version)) { + // Add license label + value += (copyrightLicense.hasOwnProperty('label') ? copyrightLicense.label : copyrightLicense); + } + + // Check for version info + var versionInfo; + if (copyrightLicense.versions) { + if (copyrightLicense.versions.default && (!version || !copyrightLicense.versions[version])) { + version = copyrightLicense.versions.default; + } + if (version && copyrightLicense.versions[version]) { + versionInfo = copyrightLicense.versions[version]; + } + } + + if (versionInfo) { + // Add license version + if (value) { + value += ' '; + } + value += (versionInfo.hasOwnProperty('label') ? versionInfo.label : versionInfo); + } + + // Add link if specified + var link; + if (copyrightLicense.hasOwnProperty('link')) { + link = copyrightLicense.link.replace(':version', copyrightLicense.linkVersions ? copyrightLicense.linkVersions[version] : version); + } + else if (versionInfo && copyrightLicense.hasOwnProperty('link')) { + link = versionInfo.link; + } + if (link) { + value = '' + value + ''; + } + + // Generate parenthesis + var parenthesis = ''; + if (license !== 'PD' && license !== 'C') { + parenthesis += license; + } + if (version && version !== 'CC0 1.0') { + if (parenthesis && license !== 'GNU GPL') { + parenthesis += ' '; + } + parenthesis += version; + } + if (parenthesis) { + value += ' (' + parenthesis + ')'; + } + if (license === 'C') { + value += ' ©'; + } + + return value; + }; + + if (copyright !== undefined) { + // Add the extra fields + for (var field in extraFields) { + if (extraFields.hasOwnProperty(field)) { + copyright[field] = extraFields[field]; + } + } + + if (order === undefined) { + // Set default order + order = ['contentType', 'title', 'license', 'author', 'year', 'source', 'licenseExtras', 'changes']; + } + + for (var i = 0; i < order.length; i++) { + var fieldName = order[i]; + if (copyright[fieldName] !== undefined && copyright[fieldName] !== '') { + var humanValue = copyright[fieldName]; + if (fieldName === 'license') { + humanValue = humanizeLicense(copyright.license, copyright.version); + } + if (fieldName === 'source') { + humanValue = (humanValue) ? '' + humanValue + '' : undefined; + } + list.add(new H5P.Field(getLabel(fieldName), humanValue)); + } + } + } + + /** + * Set thumbnail. + * + * @param {H5P.Thumbnail} newThumbnail + */ + this.setThumbnail = function (newThumbnail) { + thumbnail = newThumbnail; + }; + + /** + * Checks if this copyright is undisclosed. + * I.e. only has the license attribute set, and it's undisclosed. + * + * @returns {boolean} + */ + this.undisclosed = function () { + if (list.size() === 1) { + var field = list.get(0); + if (field.getLabel() === getLabel('license') && field.getValue() === humanizeLicense('U')) { + return true; + } + } + return false; + }; + + /** + * Print media copyright. + * + * @returns {string} HTML. + */ + this.toString = function () { + var html = ''; + + if (this.undisclosed()) { + return html; // No need to print a copyright with a single undisclosed license. + } + + if (thumbnail !== undefined) { + html += thumbnail; + } + html += list; + + if (html !== '') { + html = ''; + } + + return html; + }; +}; + +/** + * A simple and elegant class for creating thumbnails of images. + * + * @class + * @param {string} source + * @param {number} width + * @param {number} height + */ +H5P.Thumbnail = function (source, width, height) { + var thumbWidth, thumbHeight = 100; + if (width !== undefined) { + thumbWidth = Math.round(thumbHeight * (width / height)); + } + + /** + * Print thumbnail. + * + * @returns {string} HTML. + */ + this.toString = function () { + return '' + H5P.t('thumbnail') + ''; + }; +}; + +/** + * Simple data structure class for storing a single field. + * + * @class + * @param {string} label + * @param {string} value + */ +H5P.Field = function (label, value) { + /** + * Public. Get field label. + * + * @returns {String} + */ + this.getLabel = function () { + return label; + }; + + /** + * Public. Get field value. + * + * @returns {String} + */ + this.getValue = function () { + return value; + }; +}; + +/** + * Simple class for creating a definition list. + * + * @class + */ +H5P.DefinitionList = function () { + var fields = []; + + /** + * Add field to list. + * + * @param {H5P.Field} field + */ + this.add = function (field) { + fields.push(field); + }; + + /** + * Get Number of fields. + * + * @returns {number} + */ + this.size = function () { + return fields.length; + }; + + /** + * Get field at given index. + * + * @param {number} index + * @returns {H5P.Field} + */ + this.get = function (index) { + return fields[index]; + }; + + /** + * Print definition list. + * + * @returns {string} HTML. + */ + this.toString = function () { + var html = ''; + for (var i = 0; i < fields.length; i++) { + var field = fields[i]; + html += '
      ' + field.getLabel() + '
      ' + field.getValue() + '
      '; + } + return (html === '' ? html : '
      ' + html + '
      '); + }; +}; + +/** + * THIS FUNCTION/CLASS IS DEPRECATED AND WILL BE REMOVED. + * + * Helper object for keeping coordinates in the same format all over. + * + * @deprecated + * Will be removed march 2016. + * @class + * @param {number} x + * @param {number} y + * @param {number} w + * @param {number} h + */ +H5P.Coords = function (x, y, w, h) { + if ( !(this instanceof H5P.Coords) ) + return new H5P.Coords(x, y, w, h); + + /** @member {number} */ + this.x = 0; + /** @member {number} */ + this.y = 0; + /** @member {number} */ + this.w = 1; + /** @member {number} */ + this.h = 1; + + if (typeof(x) === 'object') { + this.x = x.x; + this.y = x.y; + this.w = x.w; + this.h = x.h; + } + else { + if (x !== undefined) { + this.x = x; + } + if (y !== undefined) { + this.y = y; + } + if (w !== undefined) { + this.w = w; + } + if (h !== undefined) { + this.h = h; + } + } + return this; +}; + +/** + * Parse library string into values. + * + * @param {string} library + * library in the format "machineName majorVersion.minorVersion" + * @returns {Object} + * library as an object with machineName, majorVersion and minorVersion properties + * return false if the library parameter is invalid + */ +H5P.libraryFromString = function (library) { + var regExp = /(.+)\s(\d+)\.(\d+)$/g; + var res = regExp.exec(library); + if (res !== null) { + return { + 'machineName': res[1], + 'majorVersion': parseInt(res[2]), + 'minorVersion': parseInt(res[3]) + }; + } + else { + return false; + } +}; + +/** + * Get the path to the library + * + * @param {string} library + * The library identifier in the format "machineName-majorVersion.minorVersion". + * @returns {string} + * The full path to the library. + */ +H5P.getLibraryPath = function (library) { + if (H5PIntegration.urlLibraries !== undefined) { + // This is an override for those implementations that has a different libraries URL, e.g. Moodle + return H5PIntegration.urlLibraries + '/' + library; + } + else { + return H5PIntegration.url + '/libraries/' + library; + } +}; + +/** + * Recursivly clone the given object. + * + * @param {Object|Array} object + * Object to clone. + * @param {boolean} [recursive] + * @returns {Object|Array} + * A clone of object. + */ +H5P.cloneObject = function (object, recursive) { + // TODO: Consider if this needs to be in core. Doesn't $.extend do the same? + var clone = object instanceof Array ? [] : {}; + + for (var i in object) { + if (object.hasOwnProperty(i)) { + if (recursive !== undefined && recursive && typeof object[i] === 'object') { + clone[i] = H5P.cloneObject(object[i], recursive); + } + else { + clone[i] = object[i]; + } + } + } + + return clone; +}; + +/** + * Remove all empty spaces before and after the value. + * + * @param {string} value + * @returns {string} + */ +H5P.trim = function (value) { + return value.replace(/^\s+|\s+$/g, ''); + + // TODO: Only include this or String.trim(). What is best? + // I'm leaning towards implementing the missing ones: http://kangax.github.io/compat-table/es5/ + // So should we make this function deprecated? +}; + +/** + * Check if JavaScript path/key is loaded. + * + * @param {string} path + * @returns {boolean} + */ +H5P.jsLoaded = function (path) { + H5PIntegration.loadedJs = H5PIntegration.loadedJs || []; + return H5P.jQuery.inArray(path, H5PIntegration.loadedJs) !== -1; +}; + +/** + * Check if styles path/key is loaded. + * + * @param {string} path + * @returns {boolean} + */ +H5P.cssLoaded = function (path) { + H5PIntegration.loadedCss = H5PIntegration.loadedCss || []; + return H5P.jQuery.inArray(path, H5PIntegration.loadedCss) !== -1; +}; + +/** + * Shuffle an array in place. + * + * @param {Array} array + * Array to shuffle + * @returns {Array} + * The passed array is returned for chaining. + */ +H5P.shuffleArray = function (array) { + // TODO: Consider if this should be a part of core. I'm guessing very few libraries are going to use it. + if (!(array instanceof Array)) { + return; + } + + var i = array.length, j, tempi, tempj; + if ( i === 0 ) return false; + while ( --i ) { + j = Math.floor( Math.random() * ( i + 1 ) ); + tempi = array[i]; + tempj = array[j]; + array[i] = tempj; + array[j] = tempi; + } + return array; +}; + +/** + * Post finished results for user. + * + * @deprecated + * Do not use this function directly, trigger the finish event instead. + * Will be removed march 2016 + * @param {number} contentId + * Identifies the content + * @param {number} score + * Achieved score/points + * @param {number} maxScore + * The maximum score/points that can be achieved + * @param {number} [time] + * Reported time consumption/usage + */ +H5P.setFinished = function (contentId, score, maxScore, time) { + var validScore = typeof score === 'number' || score instanceof Number; + if (validScore && H5PIntegration.postUserStatistics === true) { + /** + * Return unix timestamp for the given JS Date. + * + * @private + * @param {Date} date + * @returns {Number} + */ + var toUnix = function (date) { + return Math.round(date.getTime() / 1000); + }; + + // Post the results + const data = { + contentId: contentId, + score: score, + maxScore: maxScore, + opened: toUnix(H5P.opened[contentId]), + finished: toUnix(new Date()), + time: time + }; + H5P.jQuery.post(H5PIntegration.ajax.setFinished, data) + .fail(function () { + H5P.offlineRequestQueue.add(H5PIntegration.ajax.setFinished, data); + }); + } +}; + +// Add indexOf to browsers that lack them. (IEs) +if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function (needle) { + for (var i = 0; i < this.length; i++) { + if (this[i] === needle) { + return i; + } + } + return -1; + }; +} + +// Need to define trim() since this is not available on older IEs, +// and trim is used in several libs +if (String.prototype.trim === undefined) { + String.prototype.trim = function () { + return H5P.trim(this); + }; +} + +/** + * Trigger an event on an instance + * + * Helper function that triggers an event if the instance supports event handling + * + * @param {Object} instance + * Instance of H5P content + * @param {string} eventType + * Type of event to trigger + * @param {*} data + * @param {Object} extras + */ +H5P.trigger = function (instance, eventType, data, extras) { + // Try new event system first + if (instance.trigger !== undefined) { + instance.trigger(eventType, data, extras); + } + // Try deprecated event system + else if (instance.$ !== undefined && instance.$.trigger !== undefined) { + instance.$.trigger(eventType); + } +}; + +/** + * Register an event handler + * + * Helper function that registers an event handler for an event type if + * the instance supports event handling + * + * @param {Object} instance + * Instance of H5P content + * @param {string} eventType + * Type of event to listen for + * @param {H5P.EventCallback} handler + * Callback that gets triggered for events of the specified type + */ +H5P.on = function (instance, eventType, handler) { + // Try new event system first + if (instance.on !== undefined) { + instance.on(eventType, handler); + } + // Try deprecated event system + else if (instance.$ !== undefined && instance.$.on !== undefined) { + instance.$.on(eventType, handler); + } +}; + +/** + * Generate random UUID + * + * @returns {string} UUID + */ +H5P.createUUID = function () { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (char) { + var random = Math.random()*16|0, newChar = char === 'x' ? random : (random&0x3|0x8); + return newChar.toString(16); + }); +}; + +/** + * Create title + * + * @param {string} rawTitle + * @param {number} maxLength + * @returns {string} + */ +H5P.createTitle = function (rawTitle, maxLength) { + if (!rawTitle) { + return ''; + } + if (maxLength === undefined) { + maxLength = 60; + } + var title = H5P.jQuery('
      ') + .text( + // Strip tags + rawTitle.replace(/(<([^>]+)>)/ig,"") + // Escape + ).text(); + if (title.length > maxLength) { + title = title.substr(0, maxLength - 3) + '...'; + } + return title; +}; + +// Wrap in privates +(function ($) { + + /** + * Creates ajax requests for inserting, updateing and deleteing + * content user data. + * + * @private + * @param {number} contentId What content to store the data for. + * @param {string} dataType Identifies the set of data for this content. + * @param {string} subContentId Identifies sub content + * @param {function} [done] Callback when ajax is done. + * @param {object} [data] To be stored for future use. + * @param {boolean} [preload=false] Data is loaded when content is loaded. + * @param {boolean} [invalidate=false] Data is invalidated when content changes. + * @param {boolean} [async=true] + */ + function contentUserDataAjax(contentId, dataType, subContentId, done, data, preload, invalidate, async) { + if (H5PIntegration.user === undefined) { + // Not logged in, no use in saving. + done('Not signed in.'); + return; + } + + var options = { + url: H5PIntegration.ajax.contentUserData.replace(':contentId', contentId).replace(':dataType', dataType).replace(':subContentId', subContentId ? subContentId : 0), + dataType: 'json', + async: async === undefined ? true : async + }; + if (data !== undefined) { + options.type = 'POST'; + options.data = { + data: (data === null ? 0 : data), + preload: (preload ? 1 : 0), + invalidate: (invalidate ? 1 : 0) + }; + } + else { + options.type = 'GET'; + } + if (done !== undefined) { + options.error = function (xhr, error) { + done(error); + }; + options.success = function (response) { + if (!response.success) { + done(response.message); + return; + } + + if (response.data === false || response.data === undefined) { + done(); + return; + } + + done(undefined, response.data); + }; + } + + $.ajax(options); + } + + /** + * Get user data for given content. + * + * @param {number} contentId + * What content to get data for. + * @param {string} dataId + * Identifies the set of data for this content. + * @param {function} done + * Callback with error and data parameters. + * @param {string} [subContentId] + * Identifies which data belongs to sub content. + */ + H5P.getUserData = function (contentId, dataId, done, subContentId) { + if (!subContentId) { + subContentId = 0; // Default + } + + H5PIntegration.contents = H5PIntegration.contents || {}; + var content = H5PIntegration.contents['cid-' + contentId] || {}; + var preloadedData = content.contentUserData; + if (preloadedData && preloadedData[subContentId] && preloadedData[subContentId][dataId] !== undefined) { + if (preloadedData[subContentId][dataId] === 'RESET') { + done(undefined, null); + return; + } + try { + done(undefined, JSON.parse(preloadedData[subContentId][dataId])); + } + catch (err) { + done(err); + } + } + else { + contentUserDataAjax(contentId, dataId, subContentId, function (err, data) { + if (err || data === undefined) { + done(err, data); + return; // Error or no data + } + + // Cache in preloaded + if (content.contentUserData === undefined) { + content.contentUserData = preloadedData = {}; + } + if (preloadedData[subContentId] === undefined) { + preloadedData[subContentId] = {}; + } + preloadedData[subContentId][dataId] = data; + + // Done. Try to decode JSON + try { + done(undefined, JSON.parse(data)); + } + catch (e) { + done(e); + } + }); + } + }; + + /** + * Async error handling. + * + * @callback H5P.ErrorCallback + * @param {*} error + */ + + /** + * Set user data for given content. + * + * @param {number} contentId + * What content to get data for. + * @param {string} dataId + * Identifies the set of data for this content. + * @param {Object} data + * The data that is to be stored. + * @param {Object} [extras] + * Extra properties + * @param {string} [extras.subContentId] + * Identifies which data belongs to sub content. + * @param {boolean} [extras.preloaded=true] + * If the data should be loaded when content is loaded. + * @param {boolean} [extras.deleteOnChange=false] + * If the data should be invalidated when the content changes. + * @param {H5P.ErrorCallback} [extras.errorCallback] + * Callback with error as parameters. + * @param {boolean} [extras.async=true] + */ + H5P.setUserData = function (contentId, dataId, data, extras) { + var options = H5P.jQuery.extend(true, {}, { + subContentId: 0, + preloaded: true, + deleteOnChange: false, + async: true + }, extras); + + try { + data = JSON.stringify(data); + } + catch (err) { + if (options.errorCallback) { + options.errorCallback(err); + } + return; // Failed to serialize. + } + + var content = H5PIntegration.contents['cid-' + contentId]; + if (content === undefined) { + content = H5PIntegration.contents['cid-' + contentId] = {}; + } + if (!content.contentUserData) { + content.contentUserData = {}; + } + var preloadedData = content.contentUserData; + if (preloadedData[options.subContentId] === undefined) { + preloadedData[options.subContentId] = {}; + } + if (data === preloadedData[options.subContentId][dataId]) { + return; // No need to save this twice. + } + + preloadedData[options.subContentId][dataId] = data; + contentUserDataAjax(contentId, dataId, options.subContentId, function (error) { + if (options.errorCallback && error) { + options.errorCallback(error); + } + }, data, options.preloaded, options.deleteOnChange, options.async); + }; + + /** + * Delete user data for given content. + * + * @param {number} contentId + * What content to remove data for. + * @param {string} dataId + * Identifies the set of data for this content. + * @param {string} [subContentId] + * Identifies which data belongs to sub content. + */ + H5P.deleteUserData = function (contentId, dataId, subContentId) { + if (!subContentId) { + subContentId = 0; // Default + } + + // Remove from preloaded/cache + var preloadedData = H5PIntegration.contents['cid-' + contentId].contentUserData; + if (preloadedData && preloadedData[subContentId] && preloadedData[subContentId][dataId]) { + delete preloadedData[subContentId][dataId]; + } + + contentUserDataAjax(contentId, dataId, subContentId, undefined, null); + }; + + /** + * Function for getting content for a certain ID + * + * @param {number} contentId + * @return {Object} + */ + H5P.getContentForInstance = function (contentId) { + var key = 'cid-' + contentId; + var exists = H5PIntegration && H5PIntegration.contents && + H5PIntegration.contents[key]; + + return exists ? H5PIntegration.contents[key] : undefined; + }; + + /** + * Prepares the content parameters for storing in the clipboard. + * + * @class + * @param {Object} parameters The parameters for the content to store + * @param {string} [genericProperty] If only part of the parameters are generic, which part + * @param {string} [specificKey] If the parameters are specific, what content type does it fit + * @returns {Object} Ready for the clipboard + */ + H5P.ClipboardItem = function (parameters, genericProperty, specificKey) { + var self = this; + + /** + * Set relative dimensions when params contains a file with a width and a height. + * Very useful to be compatible with wysiwyg editors. + * + * @private + */ + var setDimensionsFromFile = function () { + if (!self.generic) { + return; + } + var params = self.specific[self.generic]; + if (!params.params.file || !params.params.file.width || !params.params.file.height) { + return; + } + + self.width = 20; // % + self.height = (params.params.file.height / params.params.file.width) * self.width; + }; + + if (!genericProperty) { + genericProperty = 'action'; + parameters = { + action: parameters + }; + } + + self.specific = parameters; + + if (genericProperty && parameters[genericProperty]) { + self.generic = genericProperty; + } + if (specificKey) { + self.from = specificKey; + } + + if (window.H5PEditor && H5PEditor.contentId) { + self.contentId = H5PEditor.contentId; + } + + if (!self.specific.width && !self.specific.height) { + setDimensionsFromFile(); + } + }; + + /** + * Store item in the H5P Clipboard. + * + * @param {H5P.ClipboardItem|*} clipboardItem + */ + H5P.clipboardify = function (clipboardItem) { + if (!(clipboardItem instanceof H5P.ClipboardItem)) { + clipboardItem = new H5P.ClipboardItem(clipboardItem); + } + H5P.setClipboard(clipboardItem); + }; + + /** + * Retrieve parsed clipboard data. + * + * @return {Object} + */ + H5P.getClipboard = function () { + return parseClipboard(); + }; + + /** + * Set item in the H5P Clipboard. + * + * @param {H5P.ClipboardItem|object} clipboardItem - Data to be set. + */ + H5P.setClipboard = function (clipboardItem) { + localStorage.setItem('h5pClipboard', JSON.stringify(clipboardItem)); + + // Trigger an event so all 'Paste' buttons may be enabled. + H5P.externalDispatcher.trigger('datainclipboard', {reset: false}); + }; + + /** + * Get config for a library + * + * @param string machineName + * @return Object + */ + H5P.getLibraryConfig = function (machineName) { + var hasConfig = H5PIntegration.libraryConfig && H5PIntegration.libraryConfig[machineName]; + return hasConfig ? H5PIntegration.libraryConfig[machineName] : {}; + }; + + /** + * Get item from the H5P Clipboard. + * + * @private + * @return {Object} + */ + var parseClipboard = function () { + var clipboardData = localStorage.getItem('h5pClipboard'); + if (!clipboardData) { + return; + } + + // Try to parse clipboard dat + try { + clipboardData = JSON.parse(clipboardData); + } + catch (err) { + console.error('Unable to parse JSON from clipboard.', err); + return; + } + + // Update file URLs and reset content Ids + recursiveUpdate(clipboardData.specific, function (path) { + var isTmpFile = (path.substr(-4, 4) === '#tmp'); + if (!isTmpFile && clipboardData.contentId && !path.match(/^https?:\/\//i)) { + // Comes from existing content + + if (H5PEditor.contentId) { + // .. to existing content + return '../' + clipboardData.contentId + '/' + path; + } + else { + // .. to new content + return (H5PEditor.contentRelUrl ? H5PEditor.contentRelUrl : '../content/') + clipboardData.contentId + '/' + path; + } + } + return path; // Will automatically be looked for in tmp folder + }); + + + if (clipboardData.generic) { + // Use reference instead of key + clipboardData.generic = clipboardData.specific[clipboardData.generic]; + } + + return clipboardData; + }; + + /** + * Update file URLs and reset content IDs. + * Useful when copying content. + * + * @private + * @param {object} params Reference + * @param {function} handler Modifies the path to work when pasted + */ + var recursiveUpdate = function (params, handler) { + for (var prop in params) { + if (params.hasOwnProperty(prop) && params[prop] instanceof Object) { + var obj = params[prop]; + if (obj.path !== undefined && obj.mime !== undefined) { + obj.path = handler(obj.path); + } + else { + if (obj.library !== undefined && obj.subContentId !== undefined) { + // Avoid multiple content with same ID + delete obj.subContentId; + } + recursiveUpdate(obj, handler); + } + } + } + }; + + // Init H5P when page is fully loadded + $(document).ready(function () { + + window.addEventListener('storage', function (event) { + // Pick up clipboard changes from other tabs + if (event.key === 'h5pClipboard') { + // Trigger an event so all 'Paste' buttons may be enabled. + H5P.externalDispatcher.trigger('datainclipboard', {reset: event.newValue === null}); + } + }); + + var ccVersions = { + 'default': '4.0', + '4.0': H5P.t('licenseCC40'), + '3.0': H5P.t('licenseCC30'), + '2.5': H5P.t('licenseCC25'), + '2.0': H5P.t('licenseCC20'), + '1.0': H5P.t('licenseCC10'), + }; + + /** + * Maps copyright license codes to their human readable counterpart. + * + * @type {Object} + */ + H5P.copyrightLicenses = { + 'U': H5P.t('licenseU'), + 'CC BY': { + label: H5P.t('licenseCCBY'), + link: 'http://creativecommons.org/licenses/by/:version', + versions: ccVersions + }, + 'CC BY-SA': { + label: H5P.t('licenseCCBYSA'), + link: 'http://creativecommons.org/licenses/by-sa/:version', + versions: ccVersions + }, + 'CC BY-ND': { + label: H5P.t('licenseCCBYND'), + link: 'http://creativecommons.org/licenses/by-nd/:version', + versions: ccVersions + }, + 'CC BY-NC': { + label: H5P.t('licenseCCBYNC'), + link: 'http://creativecommons.org/licenses/by-nc/:version', + versions: ccVersions + }, + 'CC BY-NC-SA': { + label: H5P.t('licenseCCBYNCSA'), + link: 'http://creativecommons.org/licenses/by-nc-sa/:version', + versions: ccVersions + }, + 'CC BY-NC-ND': { + label: H5P.t('licenseCCBYNCND'), + link: 'http://creativecommons.org/licenses/by-nc-nd/:version', + versions: ccVersions + }, + 'CC0 1.0': { + label: H5P.t('licenseCC010'), + link: 'https://creativecommons.org/publicdomain/zero/1.0/' + }, + 'GNU GPL': { + label: H5P.t('licenseGPL'), + link: 'http://www.gnu.org/licenses/gpl-:version-standalone.html', + linkVersions: { + 'v3': '3.0', + 'v2': '2.0', + 'v1': '1.0' + }, + versions: { + 'default': 'v3', + 'v3': H5P.t('licenseV3'), + 'v2': H5P.t('licenseV2'), + 'v1': H5P.t('licenseV1') + } + }, + 'PD': { + label: H5P.t('licensePD'), + versions: { + 'CC0 1.0': { + label: H5P.t('licenseCC010'), + link: 'https://creativecommons.org/publicdomain/zero/1.0/' + }, + 'CC PDM': { + label: H5P.t('licensePDM'), + link: 'https://creativecommons.org/publicdomain/mark/1.0/' + } + } + }, + 'ODC PDDL': 'Public Domain Dedication and Licence', + 'CC PDM': { + label: H5P.t('licensePDM'), + link: 'https://creativecommons.org/publicdomain/mark/1.0/' + }, + 'C': H5P.t('licenseC'), + }; + + /** + * Indicates if H5P is embedded on an external page using iframe. + * @member {boolean} H5P.externalEmbed + */ + + // Relay events to top window. This must be done before H5P.init + // since events may be fired on initialization. + if (H5P.isFramed && H5P.externalEmbed === false) { + H5P.externalDispatcher.on('*', function (event) { + window.parent.H5P.externalDispatcher.trigger.call(this, event); + }); + } + + /** + * Prevent H5P Core from initializing. Must be overriden before document ready. + * @member {boolean} H5P.preventInit + */ + if (!H5P.preventInit) { + // Note that this start script has to be an external resource for it to + // load in correct order in IE9. + H5P.init(document.body); + } + + if (H5PIntegration.saveFreq !== false) { + // When was the last state stored + var lastStoredOn = 0; + // Store the current state of the H5P when leaving the page. + var storeCurrentState = function () { + // Make sure at least 250 ms has passed since last save + var currentTime = new Date().getTime(); + if (currentTime - lastStoredOn > 250) { + lastStoredOn = currentTime; + for (var i = 0; i < H5P.instances.length; i++) { + var instance = H5P.instances[i]; + if (instance.getCurrentState instanceof Function || + typeof instance.getCurrentState === 'function') { + var state = instance.getCurrentState(); + if (state !== undefined) { + // Async is not used to prevent the request from being cancelled. + H5P.setUserData(instance.contentId, 'state', state, {deleteOnChange: true, async: false}); + } + } + } + } + }; + // iPad does not support beforeunload, therefore using unload + H5P.$window.one('beforeunload unload', function () { + // Only want to do this once + H5P.$window.off('pagehide beforeunload unload'); + storeCurrentState(); + }); + // pagehide is used on iPad when tabs are switched + H5P.$window.on('pagehide', storeCurrentState); + } + }); + +})(H5P.jQuery); diff --git a/apps/server/static-assets/h5p/core/js/jquery.js b/apps/server/static-assets/h5p/core/js/jquery.js new file mode 100644 index 00000000000..a05d5568b9c --- /dev/null +++ b/apps/server/static-assets/h5p/core/js/jquery.js @@ -0,0 +1,20 @@ +/*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license +*/(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML="
      a",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="
      t
      ",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="
      ",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj; +return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="
      ",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||st.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&>(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/
      ","
      "],tr:[2,"","
      "],col:[2,"","
      "],td:[3,"","
      "],_default:b.support.htmlSerialize?[0,"",""]:[1,"X
      ","
      "]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?""!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l) +}b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("