Best JavaScript code snippet using qawolf
mediaTasksPlugin.ts
Source:mediaTasksPlugin.ts
1import { ipcMain, splayerx, IpcMainEvent } from 'electron';2import { existsSync } from 'fs';3import { outputFile } from 'fs-extra';4function reply(event: IpcMainEvent, channel: string, ...args: unknown[]) {5 if (event.sender && !event.sender.isDestroyed()) event.reply(channel, ...args);6}7/**8 * Proxied splayerx module to prevent main process crash9 */10const splayerxProxy = new Proxy(splayerx, {11 get(obj, prop) {12 if (!(prop in obj)) return undefined;13 const originMember = obj[prop];14 if (typeof originMember === 'function') {15 const proxiedFunction = function proxiedFunction(...args: unknown[]) {16 try {17 return originMember.apply(obj, args);18 } catch (ex) {19 console.error(ex, prop, args);20 return undefined;21 }22 };23 return proxiedFunction.bind(obj);24 }25 return originMember;26 },27});28export default function registerMediaTasks() {29 ipcMain.on('media-info-request', (event, path) => {30 if (existsSync(path)) {31 splayerxProxy.getMediaInfo(path, info => reply(event, 'media-info-reply', null, info));32 } else {33 reply(event, 'media-info-reply', 'File does not exist.');34 }35 });36 ipcMain.on('snapshot-request', (event,37 videoPath, imagePath,38 timeString,39 width, height) => {40 if (existsSync(imagePath)) {41 reply(event, 'snapshot-reply', null, imagePath);42 } else if (existsSync(videoPath)) {43 splayerxProxy.snapshotVideo(44 videoPath, imagePath,45 timeString,46 width.toString(), height.toString(),47 (err) => {48 setTimeout(() => { // fix "Waiting for the task completion." from electron.splayerx49 if (err === '0' && existsSync(imagePath)) {50 reply(event, 'snapshot-reply', null, imagePath);51 } else {52 if (typeof err !== 'string') err = `${err}, type: ${typeof err}`;53 reply(event, 'snapshot-reply', `snapshot-reply: ${err}`);54 }55 }, 5);56 },57 );58 } else {59 reply(event, 'snapshot-reply', 'File does not exist.');60 }61 });62 let lastVideoPath = '';63 let lastStreamIndex = -1;64 const videoSubtitlesMap: Map<string, Map<number, {65 path: string,66 metadata: string,67 position: number,68 cache: Buffer,69 finished: boolean,70 }>> = new Map();71 ipcMain.on('subtitle-metadata-request', async (event: IpcMainEvent, videoPath: string, streamIndex: number, subtitlePath: string) => {72 if ((lastVideoPath || lastStreamIndex !== -1)73 && (lastVideoPath !== videoPath || lastStreamIndex !== streamIndex)) {74 await splayerxProxy.stopExtractSubtitles();75 }76 lastVideoPath = videoPath;77 lastStreamIndex = streamIndex;78 if (!videoSubtitlesMap.has(videoPath)) videoSubtitlesMap.set(videoPath, new Map());79 const streamSubtitlesMap = videoSubtitlesMap.get(videoPath);80 if (streamSubtitlesMap) {81 const subtitle = streamSubtitlesMap.get(streamIndex) || {82 path: subtitlePath,83 metadata: '',84 position: 0,85 finished: false,86 cache: Buffer.alloc(0),87 };88 if (existsSync(subtitlePath) || subtitle.finished) {89 delete subtitle.cache;90 subtitle.finished = true;91 reply(event, 'subtitle-metadata-reply', undefined, subtitle.finished);92 } else if (!subtitle.metadata) {93 splayerxProxy.extractSubtitles(videoPath, streamIndex, 0, false, 1,94 async (error, pos, isImage, data) => {95 if (pos) subtitle.position = pos;96 if (data) {97 if (isImage) {98 subtitle.metadata = data.subarray(4, 4 + data.readUInt32LE(0)).toString('utf8');99 } else {100 subtitle.metadata = data.toString('utf8')101 .replace(/\n(Dialogue|Comment)[\s\S]*/g, '')102 .split(/\r?\n/)103 .join('\n');104 }105 subtitle.cache = data;106 }107 if (error === 'EOF') {108 try {109 await outputFile(subtitle.path, isImage ? subtitle.cache : subtitle.cache.toString('utf8'));110 delete subtitle.cache;111 subtitle.finished = true;112 reply(event, 'subtitle-metadata-reply', undefined, subtitle.finished, subtitle.path);113 } catch (err) {114 reply(event, 'subtitle-metadata-reply', err);115 }116 } else if (error || !data) {117 reply(event, 'subtitle-metadata-reply', new Error(error || 'Missing subtitle data.'));118 }119 reply(event, 'subtitle-metadata-reply', undefined, subtitle.finished, subtitle.metadata);120 });121 } else {122 reply(event, 'subtitle-metadata-reply', undefined, subtitle.finished, subtitle.metadata);123 }124 streamSubtitlesMap.set(streamIndex, subtitle);125 }126 });127 ipcMain.on('subtitle-cache-request', async (event: IpcMainEvent, videoPath: string, streamIndex: number) => {128 let needRemoveMetadata = false;129 if ((lastVideoPath || lastStreamIndex !== -1)130 && (lastVideoPath !== videoPath || lastStreamIndex !== streamIndex)) {131 await splayerxProxy.stopExtractSubtitles();132 needRemoveMetadata = true;133 }134 lastVideoPath = videoPath;135 lastStreamIndex = streamIndex;136 const streamSubtitlesMap = videoSubtitlesMap.get(videoPath);137 if (streamSubtitlesMap) {138 const subtitle = streamSubtitlesMap.get(streamIndex);139 if (subtitle) {140 if (subtitle.finished) reply(event, 'subtitle-cache-reply', undefined, subtitle.path);141 else {142 splayerxProxy.extractSubtitles(videoPath, streamIndex, subtitle.position, false, 20,143 async (error, pos, isImage, data) => {144 if (pos) subtitle.position = pos;145 if (needRemoveMetadata) {146 if (isImage) {147 const metadataLength = data.readUInt32LE(0);148 if (metadataLength + 4 <= data.length) {149 const metadataInfo = data.subarray(4, 4 + data.readUInt32LE(0)).toString('utf8');150 if (metadataInfo === subtitle.metadata) data = data.slice(4 + metadataLength);151 }152 } else {153 const metadataInfo = data.toString('utf8')154 .replace(/\n(Dialogue|Comment)[\s\S]*/g, '')155 .split(/\r?\n/)156 .join('\n');157 if (metadataInfo === subtitle.metadata) {158 data = data.slice(Buffer.from(metadataInfo).length);159 }160 }161 }162 if (data) subtitle.cache = Buffer.concat([subtitle.cache, data]);163 if (isImage && data) {164 const { length } = data;165 let offset = 0;166 while (offset < length) {167 const pngSize = data.readUInt32LE(24);168 console.log('Png Size:', pngSize);169 offset += (28 + pngSize);170 }171 }172 if (error === 'EOF') {173 try {174 await outputFile(subtitle.path, isImage ? subtitle.cache : subtitle.cache.toString('utf8'));175 delete subtitle.cache;176 subtitle.finished = true;177 reply(event, 'subtitle-cache-reply', undefined, subtitle.path);178 } catch (err) {179 reply(event, 'subtitle-cache-reply', err);180 }181 } else if (error) {182 reply(event, 'subtitle-cache-reply', new Error(error));183 } else {184 reply(event, 'subtitle-cache-reply', undefined, undefined);185 }186 streamSubtitlesMap.set(streamIndex, subtitle);187 });188 }189 } else reply(event, 'subtitle-cache-reply', new Error('Missing subtitle entry, should request metadata first.'));190 } else reply(event, 'subtitle-cache-reply', new Error('Missing videoPath entry, should request metadata first.'));191 });192 ipcMain.on('subtitle-stream-request', (event: IpcMainEvent, videoPath: string, streamIndex: number, time: number) => {193 const streamSubtitlesMap = videoSubtitlesMap.get(videoPath);194 if (streamSubtitlesMap) {195 const subtitle = streamSubtitlesMap.get(streamIndex);196 if (subtitle) {197 splayerxProxy.extractSubtitles(videoPath, streamIndex, time, true, 20,198 (error, pos, isImage, data) => {199 if (data) {200 reply(event, 'subtitle-stream-reply', undefined, data);201 } else {202 reply(event, 'subtitle-stream-reply', new Error(!error || !data ? 'Missing subtitle data' : error));203 }204 });205 } else reply(event, 'subtitle-stream-reply', new Error('Missing subtitle entry, should request metadata first.'));206 } else reply(event, 'subtitle-stream-reply', new Error('Missing videoPath entry, should request metadata first.'));207 });208 ipcMain.on('subtitle-destroy-request', async (event: IpcMainEvent, videoPath: string, streamIndex: number) => {209 const streamSubtitlesMap = videoSubtitlesMap.get(videoPath);210 if (streamSubtitlesMap) {211 const subtitle = streamSubtitlesMap.get(streamIndex);212 if (subtitle) {213 await splayerxProxy.stopExtractSubtitles();214 lastVideoPath = '';215 lastStreamIndex = -1;216 }217 }218 reply(event, 'subtitle-destroy-reply');219 });220 ipcMain.on('thumbnail-request', (event,221 videoPath, imagePath, interval,222 thumbnailWidth, cols) => {223 if (existsSync(imagePath)) {224 reply(event, 'thumbnail-reply', null, imagePath, videoPath);225 } else if (existsSync(videoPath)) {226 splayerxProxy.generateThumbnails(227 videoPath, imagePath, interval,228 thumbnailWidth.toString(), cols.toString(), '0',229 (err) => {230 if (err === '0' && existsSync(imagePath)) {231 reply(event, 'thumbnail-reply', null, imagePath, videoPath);232 } else {233 if (typeof err !== 'string') err = `${err}, type: ${typeof err}`;234 reply(event, 'thumbnail-reply', `thumbnail-reply: ${err}`);235 }236 },237 );238 } else {239 reply(event, 'thumbnail-reply', 'File does not exist.');240 }241 });...
index.js
Source:index.js
1// Storyline definition + all settings [Path/Type/Options/..]2// Video Settings3const VideoPath = '/video/';4const VideoType = '.';5const OverlayTime = 0; // Sek6const state = {7 '1': {8 video: VideoPath + 'Akt_1' + VideoType,9 type: "question",10 question: 'Soll die Regierung VorsichtsmaÃnahmen treffen oder abwarten?',11 firstOption: {12 next: 1.1,13 response: 'Handeln',14 },15 secondOption: {16 next: 1.2,17 response: 'Abwarten',18 },19 MinMaxInfected: [0, 0],20 MinMaxDead: [0, 0],21 Overlay: OverlayTime,22 },23 '1.1': {24 video: VideoPath + 'Akt_1_1' + VideoType,25 type: "continue",26 continueStory: {27 next: '2',28 response: 'Weiter'29 },30 MinMaxInfected: [0, 0],31 MinMaxDead: [0, 0],32 },33 '1.2': {34 video: VideoPath + "Akt_1_2" + VideoType,35 type: "continue",36 continueStory: {37 next: '2',38 response: 'Weiter'39 },40 MinMaxInfected: [0, 0],41 MinMaxDead: [0, 0],42 // AKW: [1500000,2500000]43 },44// Progress Number 245 '2': {46 video: VideoPath + 'Akt_2' + VideoType,47 type: "question",48 question: 'Alle Geschäfte des nicht alltäglichen Gebrauchs schlieÃen und Ausgangsbeschränkungen?',49 firstOption: {50 next: '2.1',51 response: 'Ja'52 },53 secondOption: {54 next: '2.2',55 response: 'Nein'56 },57 // Setting for Score58 MinMaxInfected: [1, 1],59 MinMaxDead: [0, 0],60 InfectedDelay: 20000,61 Overlay: OverlayTime,62 },63 '2.1': {64 video: VideoPath + 'Akt_2_1' + VideoType,65 type: "continue",66 continueStory: {67 next: '3.1',68 response: 'Weiter'69 },70 MinMaxInfected: [4000, 6000],71 MinMaxDead: [3, 8]72 },73 '2.2': {74 video: VideoPath + 'Akt_2_2' + VideoType,75 type: "continue",76 continueStory: {77 next: '3.2',78 response: 'Weiter'79 },80 MinMaxInfected: [9000, 11000],81 MinMaxDead: [10, 15]82 },83// Progress Number 384 '3.1': {85 video: VideoPath + "Akt_3_1" + VideoType,86 type: "question",87 question: 'Wie lange sollen die Geschäfte noch geschlossen bleiben?',88 firstOption: {89 next: '3.1.1',90 response: 'Bis Ostern (ca. 2 Wochen)'91 },92 secondOption: {93 next: '3.1.2',94 response: 'Solange bis ein Impfmittel erhältlich ist'95 },96 MinMaxInfected: [10000 , 12000],97 MinMaxDead: [90, 110],98 Overlay: OverlayTime,99 },100 '3.1.1': {101 video: VideoPath + "Akt_3_1_1" + VideoType,102 type: "question",103 question: 'Hilfspaket für Unternehmerinnen und Unternehmer?',104 firstOption: {105 next: '3.1.1.1',106 response: 'Ja'107 },108 secondOption: {109 next: '3.1.1.2',110 response: 'Nein'111 },112 // Setting for Score113 MinMaxInfected: [13000, 16000],114 MinMaxDead: [200, 300],115 Overlay: OverlayTime,116 },117 // End from 3.1.1.X118 '3.1.1.1': {119 video: VideoPath + "Akt_3_1_1_1" + VideoType,120 type: "end",121 MinMaxInfected: [0, 0],122 MinMaxDead: [400, 600]123 }, '3.1.1.2': {124 video: VideoPath + "Akt_3_1_1_2" + VideoType,125 type: "end",126 MinMaxInfected: [0, 0],127 MinMaxDead: [600, 800]128 },129 // Next Story130 '3.1.2': {131 video: VideoPath + "Akt_3_1_2" + VideoType,132 type: "question",133 question: 'Illegale Demonstrationen auflösen? Zur Not mit Gewalt?',134 firstOption: {135 next: '3.1.2.1',136 response: 'Abwarten und Deeskalieren'137 },138 secondOption: {139 next: '3.1.2.2',140 response: 'Polizeieinsatz'141 },142 MinMaxInfected: [2500, 3000],143 MinMaxDead: [350, 450],144 Overlay: OverlayTime,145 },146 //End from 3.1.2.X147 '3.1.2.1': {148 video: VideoPath + "Akt_3_1_2_1" + VideoType,149 type: "end",150 MinMaxInfected: [0, 0],151 MinMaxDead: [700, 900]152 },153 '3.1.2.2': {154 video: VideoPath + "Akt_3_1_2_2" + VideoType,155 type: "end",156 MinMaxInfected: [0, 0],157 MinMaxDead: [800, 1000]158 },159// Progress Number 4160 '3.2': {161 video: VideoPath + "Akt_3_2" + VideoType,162 type: "question",163 question: 'Soll eine Ausgangssperre über die Risikogruppe und die Hauptüberträger verhängt werden?',164 firstOption: {165 next: '3.2.1',166 response: 'Ja'167 },168 secondOption: {169 next: '3.2.2',170 response: 'Nein'171 },172 MinMaxInfected: [30600, 37400],173 MinMaxDead: [580, 720],174 Overlay: OverlayTime,175 },176 '3.2.1': {177 video: VideoPath + "Akt_3_2_1" + VideoType,178 type: "question",179 question: 'Hilfspaket für UnternehmerInnen?',180 firstOption: {181 next: '3.2.1.1',182 response: 'Ja'183 },184 secondOption: {185 next: '3.2.1.2',186 response: 'Nein'187 },188 MinMaxInfected: [50650,62000],189 MinMaxDead: [1050, 1300]190 },191 //End from 3.2.1.X192 '3.2.1.1': {193 video: VideoPath + "Akt_3_2_1_1" + VideoType,194 type: "end",195 MinMaxInfected: [0, 0],196 MinMaxDead: [1500, 1700]197 },198 '3.2.1.2': {199 video: VideoPath + "Akt_3_2_1_2" + VideoType,200 type: "end",201 MinMaxInfected: [0, 0],202 MinMaxDead: [1500, 1760]203 },204 '3.2.2': {205 video: VideoPath + "Akt_3_2_2" + VideoType,206 type: "question",207 question: 'Soll eine Ausgangssperre über die Risikogruppe und die Hauptüberträger verhängt werden?',208 firstOption: {209 next: '3.2.2.1',210 response: 'Nein'211 },212 secondOption: {213 next: '3.2.2.2',214 response: 'Ja'215 },216 MinMaxInfected: [4200000, 4300000],217 MinMaxDead: [260000, 260600]218 },219 '3.2.2.1': {220 video: VideoPath + "Akt_3_2_2_1" + VideoType,221 type: "end",222 MinMaxInfected: [0, 0],223 MinMaxDead: [3000000, 3145000],224 AKW: [1500000,1550000],225 },226 '3.2.2.2': {227 video: VideoPath + "Akt_3_2_2_2" + VideoType,228 type: "question",229 question: 'Hilfspaket für UnternehmerInnen?',230 firstOption: {231 next: '3.2.2.2.1',232 response: 'Ja'233 },234 secondOption: {235 next: '3.2.2.2.2',236 response: 'Nein'237 },238 MinMaxInfected: [6250000, 7600000],239 MinMaxDead: [328500, 400000],240 },241 '3.2.2.2.1': {242 video: VideoPath + "Akt_3_2_2_2_1" + VideoType,243 type: "end",244 MinMaxInfected: [0, 0],245 MinMaxDead: [400000, 440000],246 },247 '3.2.2.2.2': {248 video: VideoPath + "Akt_3_2_2_2_2" + VideoType,249 type: "end",250 MinMaxInfected: [0, 0],251 MinMaxDead: [400000, 440000],252 },253};254const getters = {255 getStoryLineList: state => {256 return state;257 }258};259const mutations = {};260const actions = {};261export default {262 state,263 getters,264 mutations,265 actions...
subtitleQueue.ts
Source:subtitleQueue.ts
1import { join } from 'path';2import { ipcRenderer } from 'electron';3import { mediaQuickHash, getSubtitleDir } from '@/libs/utils';4import { Format } from '@/interfaces/ISubtitle';5import BaseMediaTaskQueue, { IMediaTask } from './baseMediaTaskQueue';6class SubtitleMetadataTask implements IMediaTask<string> {7 private videoPath: string;8 private streamIndex: number;9 private subtitlePath: string;10 public constructor(11 videoPath: string,12 streamIndex: number, subtitlePath: string,13 ) {14 this.videoPath = videoPath;15 this.streamIndex = streamIndex;16 this.subtitlePath = subtitlePath;17 }18 private static formatToExtension(format: Format) {19 switch (format) {20 case Format.AdvancedSubStationAplha:21 case Format.SagiText:22 case Format.SubRip:23 case Format.SubStationAlpha:24 case Format.WebVTT:25 return '.ass';26 case Format.SagiImage:27 return '.sis';28 default:29 throw new Error(`Unknown format: ${format}.`);30 }31 }32 public static async from(videoPath: string, streamIndex: number, format: Format) {33 const hash = await mediaQuickHash(videoPath);34 const subtitlePath = join(await getSubtitleDir(), `${hash}-${streamIndex}${SubtitleMetadataTask.formatToExtension(format)}`);35 return new SubtitleMetadataTask(videoPath, streamIndex, subtitlePath);36 }37 public getId() { return `${['metadata', this.videoPath, this.streamIndex].join('-')}`; }38 public execute(): Promise<string> {39 return new Promise((resolve, reject) => {40 ipcRenderer.send('subtitle-metadata-request', this.videoPath, this.streamIndex, this.subtitlePath);41 ipcRenderer.once('subtitle-metadata-reply', (event, error, finished, metadata) => {42 if (error) reject(error);43 else if (finished) reject(new Error('Extraction finished.'));44 else resolve(metadata);45 });46 });47 }48}49class SubtitleCacheTask implements IMediaTask<string | undefined> {50 private readonly videoPath: string;51 private readonly streamIndex: number;52 public constructor(videoPath: string, streamIndex: number) {53 this.videoPath = videoPath;54 this.streamIndex = streamIndex;55 }56 public getId() {57 return `${['cache', this.videoPath, this.streamIndex].join('-')}`;58 }59 public execute(): Promise<string | undefined> {60 return new Promise((resolve, reject) => {61 ipcRenderer.send('subtitle-cache-request', this.videoPath, this.streamIndex);62 ipcRenderer.once('subtitle-cache-reply', (event, error, path) => {63 if (error) reject(error);64 else resolve(path);65 });66 });67 }68}69class SubtitleFragmentTask implements IMediaTask<Buffer> {70 private readonly videoPath: string;71 private readonly streamIndex: number;72 private readonly videoTime: number;73 public constructor(videoPath: string, streamIndex: number, videoTime: number) {74 this.videoPath = videoPath;75 this.streamIndex = streamIndex;76 this.videoTime = videoTime;77 }78 public getId() {79 return `${[80 'fragment',81 this.videoPath,82 this.streamIndex,83 ].join('-')}`;84 }85 public execute(): Promise<Buffer> {86 return new Promise((resolve, reject) => {87 ipcRenderer.send('subtitle-stream-request', this.videoPath, this.streamIndex, this.videoTime);88 ipcRenderer.once('subtitle-stream-reply', (event, error, data) => {89 if (error) reject(error);90 else resolve(data);91 });92 });93 }94}95class SubtitleDestroyTask implements IMediaTask<void> {96 private readonly videoPath: string;97 private readonly streamIndex: number;98 public constructor(videoPath: string, streamIndex: number) {99 this.videoPath = videoPath;100 this.streamIndex = streamIndex;101 }102 public getId() {103 return `${['finished', this.videoPath, this.streamIndex].join('-')}`;104 }105 public execute(): Promise<void> {106 return new Promise((resolve, reject) => {107 ipcRenderer.send('subtitle-destroy-request', this.videoPath, this.streamIndex);108 ipcRenderer.once('subtitle-destroy-reply', (event, error) => {109 if (error) reject(error);110 else resolve();111 });112 });113 }114}115export default class SubtitleQueue extends BaseMediaTaskQueue {116 public getSubtitleMetadata(videoPath: string, streamIndex: number, format: Format) {117 return SubtitleMetadataTask.from(videoPath, streamIndex, format)118 .then(task => super.addTask(task, { piority: 3 }));119 }120 public cacheSubtitle(videoPath: string, streamIndex: number) {121 return super.addTask(new SubtitleCacheTask(videoPath, streamIndex), { piority: 1 });122 }123 public getSubtitleFragment(videoPath: string, streamIndex: number, videoTime: number) {124 return super.addTask(125 new SubtitleFragmentTask(videoPath, streamIndex, videoTime),126 { piority: 2 },127 );128 }129 public stopSubtitleExtraction(videoPath: string, streamIndex: number) {130 const task = new SubtitleDestroyTask(videoPath, streamIndex);131 this.pendingTasks132 .filter(({ id }) => new RegExp(`${videoPath}-${streamIndex}`).test(id))133 .forEach(({ id }) => this.cancelTask(id));134 return super.addTask(task, { piority: 4 });135 }...
videos.js
Source:videos.js
1const fs = require("fs");2const express = require("express");3const router = express.Router();4const path = require("path");5const genThumbnail = require("simple-thumbnail");6const { Writable } = require("stream");7const allowedExtension = [".mov", ".mp4"];8// writable stream9let thumbnail64 = [];10let thumbnail128 = [];11let thumbnail256 = [];12let thumbnail64Writable = new Writable({13 write: (chunk, encoding, next) => {14 thumbnail64.push(chunk);15 next();16 },17});18let thumbnail128Writable = new Writable({19 write: (chunk, encoding, next) => {20 thumbnail128.push(chunk);21 next();22 },23});24let thumbnail256Writable = new Writable({25 write: (chunk, encoding, next) => {26 thumbnail256.push(chunk);27 next();28 },29});30const { video, category } = require("../models");31router.get("/", async (req, res) => {32 const videos = await video.findAll({33 raw: true,34 include: [35 {36 model: category,37 as: "category",38 },39 ],40 });41 res.json(videos);42});43router.get("/videoPlay", async (req, res) => {44 const range = req.headers.range;45 if (!range) return res.status(400).send("Requires Range header");46 const videoId = req.query.videoId;47 if (!videoId) return res.status(400).send("Requires Video Id");48 const videoPath = (await video.findByPk(videoId))?.dataValues?.path;49 if (!videoPath) return res.status(400).send("Video not found");50 const options = {};51 let start;52 let end;53 const bytesPrefix = "bytes=";54 if (range.startsWith(bytesPrefix)) {55 const bytesRange = range.substring(bytesPrefix.length);56 const parts = bytesRange.split("-");57 if (parts.length === 2) {58 const rangeStart = parts[0] && parts[0].trim();59 if (rangeStart && rangeStart.length > 0) {60 options.start = start = parseInt(rangeStart);61 }62 const rangeEnd = parts[1] && parts[1].trim();63 if (rangeEnd && rangeEnd.length > 0) {64 options.end = end = parseInt(rangeEnd);65 }66 }67 }68 res.setHeader("content-type", "video/mp4");69 fs.stat(videoPath, (err, stat) => {70 if (err) {71 console.error(`File stat error for ${videoPath}.`);72 console.error(err);73 res.sendStatus(500);74 return;75 }76 let contentLength = stat.size;77 if (req.method === "HEAD") {78 res.statusCode = 200;79 res.setHeader("accept-ranges", "bytes");80 res.setHeader("content-length", contentLength);81 res.end();82 } else {83 let retrievedLength;84 if (start !== undefined && end !== undefined) {85 retrievedLength = end + 1 - start;86 } else if (start !== undefined) {87 retrievedLength = contentLength - start;88 } else if (end !== undefined) {89 retrievedLength = end + 1;90 } else {91 retrievedLength = contentLength;92 }93 res.statusCode = start !== undefined || end !== undefined ? 206 : 200;94 res.setHeader("content-length", retrievedLength);95 if (range !== undefined) {96 res.setHeader(97 "content-range",98 `bytes ${start || 0}-${end || contentLength - 1}/${contentLength}`99 );100 res.setHeader("accept-ranges", "bytes");101 }102 const fileStream = fs.createReadStream(videoPath, options);103 fileStream.on("error", (error) => {104 console.log(`Error reading file ${videoPath}.`);105 console.log(error);106 res.sendStatus(500);107 });108 fileStream.pipe(res);109 }110 });111});112router.post("/", async (req, res) => {113 if (!req.files) return res.status(400).send("No files were uploaded.");114 const file = req.files.file;115 const fileInfo = JSON.parse(req.body.fileInfo);116 const extension = path.extname(file.name).toLowerCase();117 if (!allowedExtension.includes(extension))118 return res.status(422).send("Invalid File");119 const videoPath = `./public/videos/${Date.now()}_${file.name}`;120 file.mv(videoPath, (err) => {121 if (err) return res.status(500).send(err);122 });123 try {124 // Create thumbnails125 await genThumbnail(videoPath, thumbnail64Writable, "64x64");126 await genThumbnail(videoPath, thumbnail128Writable, "128x128");127 await genThumbnail(videoPath, thumbnail256Writable, "256x256");128 } catch (err) {129 return res.status(500).send(err);130 }131 // Add video to DB132 const categoryFound = await category.findByPk(fileInfo.categoryId);133 if (categoryFound) {134 const videoData = {135 title: fileInfo.title,136 thumbnail256: Buffer.concat(thumbnail256),137 thumbnail128: Buffer.concat(thumbnail128),138 thumbnail64: Buffer.concat(thumbnail64),139 path: videoPath,140 categoryId: fileInfo.categoryId,141 };142 video143 .create(videoData)144 .then((video) => {145 return res.status(200).json(video.dataValues);146 })147 .catch(res.status(500).send);148 } else {149 return res.status(404).send("Video category not found");150 }151});...
video-main.js
Source:video-main.js
1layui.use(['element','carousel','layer'], function(){2 var element = layui.element;3 var carousel = layui.carousel;4 var layer = layui.layer;5 var scrollTop;6 //建é å®ä¾7 //$("#example_video_1").hide();8 // window.onload = function (){ 9 // window.scroll(0,500);10 // // if (document.cookie.match(/scrollTop=([^;]+)(;|$)/) != null) { 11 // // var arr = document.cookie.match(/scrollTop=([^;]+)(;|$)/); //cookiesä¸ä¸ä¸ºç©ºï¼å读åæ»å¨æ¡ä½ç½® 12 // // console.log(arr);13 // // document.documentElement.scrollTop = parseInt(arr[1]); 14 // // document.body.scrollTop = parseInt(arr[1]); 15 // // } 16 // }17 18 carousel.render({19 elem: '#test1'20 ,width: '95%'21 ,height: '500px' //设置容å¨å®½åº¦22 ,arrow: 'always' //å§ç»æ¾ç¤ºç®å¤´23 ,interval: '5000'24 ,arrow: 'hover'25 //,anim: 'updown' //åæ¢å¨ç»æ¹å¼26 });27 $('#scene').parallax();28 29 $(".vjs-default-skin").hide();30 $(".video-thumbnail").on("click",function(){31 var videoName ='';32 var divHtmlHead = '<video id="example_video" class="video-js vjs-default-skin" style="margin-left: 5080px;" controls preload="auto" width="100%" height="100%" data-setup="{}" ><source src="';33 var divHtmlEnd = '" type="video/mp4" /></video>';34 if (this.id == "video-1-1") {videoName = videoPath[0];}35 else if (this.id == "video-1-2") {videoName = videoPath[1];}36 else if (this.id == "video-1-3") {videoName = videoPath[2];}37 else if (this.id == "video-1-4") {videoName = videoPath[3];}38 else if (this.id == "video-1-5") {videoName = videoPath[4];}39 else if (this.id == "video-1-6") {videoName = videoPath[5];}40 else if (this.id == "video-2-1") {videoName = videoPath[6];}41 else if (this.id == "video-2-2") {videoName = videoPath[7];}42 else if (this.id == "video-2-3") {videoName = videoPath[8];}43 else if (this.id == "video-2-4") {videoName = videoPath[9];}44 else if (this.id == "video-2-5") {videoName = videoPath[10];}45 else if (this.id == "video-2-6") {videoName = videoPath[11];}46 else if (this.id == "video-3-1") {videoName = videoPath[12];}47 else if (this.id == "video-3-2") {videoName = videoPath[13];}48 else if (this.id == "video-3-3") {videoName = videoPath[14];}49 else if (this.id == "video-3-4") {videoName = videoPath[15];}50 else if (this.id == "video-3-5") {videoName = videoPath[16];}51 else if (this.id == "video-3-6") {videoName = videoPath[17];}52 else if (this.id == "video-4-1") {videoName = videoPath[18];}53 else if (this.id == "video-4-2") {videoName = videoPath[19];}54 else if (this.id == "video-4-3") {videoName = videoPath[20];}55 else if (this.id == "video-4-4") {videoName = videoPath[21];}56 else if (this.id == "video-4-5") {videoName = videoPath[22];}57 else if (this.id == "video-4-6") {videoName = videoPath[23];}58 $("#video-div").empty();59 var html = divHtmlHead + videoName + divHtmlEnd60 console.log(html);61 $("#video-div").append(html);62 $(".vjs-default-skin").css("margin-left","0px");63 layer.open({64 type: 1,65 title: '',66 content: $(".vjs-default-skin"),67 area: ['70%', '70%'],68 shadeClose: false,69 cancel: function(){70 $("#video-div").empty();71 $(".layui-layer-shade").remove();72 // document.cookie ="scrollTop=" + 0;73 // document.cookie ="scrollTop=" + (-$(".site-inline").offset().top + 60);74 // console.log(scrollTop);75 // location.reload();76 // console.log(document.documentElement.scrollTop);77 // console.log(document.body.scrollTop);78 }79 }); 80 });81 //⦠...
Using AI Code Generation
1const qawolf = require("qawolf");2const browser = await qawolf.launch();3const context = browser.defaultBrowserContext();4const page = await qawolf.createPage(browser);5await qawolf.scroll(page, "html", { x: 0, y: 0 });6await page.click("text=Start recording");7await qawolf.scroll(page, "html", { x: 0, y: 0 });8await page.click("text=Stop recording");9await qawolf.scroll(page, "html", { x: 0, y: 0 });10await page.click("text=Start recording");11await qawolf.scroll(page, "html", { x: 0, y: 0 });12await page.click("text=Stop recording");13await qawolf.scroll(page, "html", { x: 0, y: 0 });14await page.click("text=Start recording");15await qawolf.scroll(page, "html", { x: 0, y: 0 });16await page.click("text=Stop recording");17await qawolf.scroll(page, "html", { x: 0, y: 0 });18await page.click("text=Start recording");19await qawolf.scroll(page, "html", { x: 0, y: 0 });20await page.click("text=Stop recording");21await qawolf.scroll(page, "html", { x: 0, y: 0 });22await page.click("text=Start recording");23await qawolf.scroll(page, "html", { x: 0, y: 0 });24await page.click("text=Stop recording");25await qawolf.scroll(page, "html", { x: 0, y: 0 });26await page.click("text=Start recording");27await qawolf.scroll(page, "html", { x: 0, y: 0 });28await page.click("text=Stop recording");29await qawolf.scroll(page, "html", { x: 0, y: 0 });30await page.click("text=Start recording");31await qawolf.scroll(page, "html", { x: 0, y: 0 });32await page.click("text=Stop
Using AI Code Generation
1const { videoPath } = require("qawolf");2const video = videoPath("test");3console.log(video);4import { videoPath } from "qawolf";5const video = videoPath("test");6console.log(video);7const { videoPath } = require("qawolf");8const video = videoPath("test");9console.log(video);10import { videoPath } from "qawolf";11const video = videoPath("test");12console.log(video);13const { video } = require("qawolf");14const video = video("test");15console.log(video);16import { video } from "qawolf";17const video = video("test");18console.log(video);19const { video } = require("qawolf");20const video = video("test");21console.log(video);22import { video } from "qawolf";23const video = video("test");24console.log(video);
Using AI Code Generation
1const qawolf = require("qawolf");2const videoPath = qawolf.videoPath("test");3console.log(videoPath);4const qawolf = require("qawolf");5const videoPath = qawolf.videoPath("test");6console.log(videoPath);7const qawolf = require("qawolf");8const videoPath = qawolf.videoPath("test");9console.log(videoPath);10const qawolf = require("qawolf");11const videoPath = qawolf.videoPath("test");12console.log(videoPath);13const qawolf = require("qawolf");14const videoPath = qawolf.videoPath("test");15console.log(videoPath);16const qawolf = require("qawolf");17const videoPath = qawolf.videoPath("test");18console.log(videoPath);19const qawolf = require("
Using AI Code Generation
1const { videoPath } = require("qawolf");2const video = videoPath("test");3console.log(video);4const { videoPath } = require("qawolf");5const video = videoPath("test");6console.log(video);7const { videoPath } = require("qawolf");8const video = videoPath("test");9console.log(video);10const { videoPath } = require("qawolf");11const video = videoPath("test");12console.log(video);13const { videoPath } = require("qawolf");14const video = videoPath("test");15console.log(video);16const { videoPath } = require("qawolf");17const video = videoPath("test");18console.log(video);19const { videoPath } = require("qawolf");20const video = videoPath("test");21console.log(video);22const { videoPath } = require("qawolf");23const video = videoPath("test");24console.log(video);25const { videoPath } = require("qawolf");26const video = videoPath("test");27console.log(video);28const { videoPath } = require("qawolf");29const video = videoPath("test");30console.log(video);31const { videoPath } = require("qawolf");32const video = videoPath("test");33console.log(video);34const { videoPath } = require("qawolf");35const video = videoPath("test");36console.log(video);
Using AI Code Generation
1const videoPath = require("qawolf").videoPath;2const videoPath1 = videoPath("test");3const videoPath = require("qawolf").videoPath;4const videoPath1 = videoPath("test");5const videoPath = require("qawolf").videoPath;6const videoPath1 = videoPath("test");7const videoPath = require("qawolf").videoPath;8const videoPath1 = videoPath("test");9const videoPath = require("qawolf").videoPath;10const videoPath1 = videoPath("test");11const videoPath = require("qawolf").videoPath;12const videoPath1 = videoPath("test");13const videoPath = require("qawolf").videoPath;14const videoPath1 = videoPath("test");15const videoPath = require("qawolf").videoPath;16const videoPath1 = videoPath("test");17const videoPath = require("qawolf").videoPath;18const videoPath1 = videoPath("test");19const videoPath = require("qawolf").videoPath;20const videoPath1 = videoPath("test");21const videoPath = require("qawolf").videoPath;22const videoPath1 = videoPath("test");23const videoPath = require("qawolf").videoPath;24const videoPath1 = videoPath("test");25const videoPath = require("qawolf").videoPath;26const videoPath1 = videoPath("test");27const videoPath = require("qawolf").videoPath;28const videoPath1 = videoPath("test");29const videoPath = require("qawolf
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!