Best JavaScript code snippet using appium-xcuitest-driver
ios-log-specs.js
Source:ios-log-specs.js
...47 await fs.writeFile(tmpSystemLog, `${message}\n`, {flag: 'a'});48 // on some slow system (e.g., Travis) need a moment49 await B.delay(500);50 spy.calledWith(`[IOS_SYSLOG_ROW] ${message}`).should.be.true;51 await log.stopCapture();52 });53 it('should rotate log buffer', async function () {54 const maxBufferSize = 10;55 const sliceSizeLimit = maxBufferSize / 2;56 sliceSizeLimit.should.be.below(maxBufferSize);57 const logRecordsCount = maxBufferSize * 2;58 logRecordsCount.should.be.above(maxBufferSize);59 let log = new IOSLog({60 sim,61 showLogs: false,62 xcodeVersion: {63 major: 764 },65 });66 log.maxBufferSize = maxBufferSize;67 log.logIdxSinceLastRequest.should.be.below(0);68 let recentLogs = await log.getLogs();69 recentLogs.should.have.lengthOf(0);70 log.logIdxSinceLastRequest.should.be.below(0);71 for (let i = 1; i <= logRecordsCount; ++i) {72 log.logRow = `${i}\n`;73 log.onOutput();74 if (i >= sliceSizeLimit && i % sliceSizeLimit === 0) {75 let previousRecentLogs = recentLogs;76 recentLogs = await log.getLogs();77 if (previousRecentLogs.length && recentLogs.length) {78 previousRecentLogs[0].message.should.not.be.equal(recentLogs[0].message);79 }80 recentLogs.should.have.lengthOf(sliceSizeLimit);81 let reminder = log.logIdxSinceLastRequest % sliceSizeLimit;82 reminder.should.equal(0);83 }84 log.logs.should.have.lengthOf(i < maxBufferSize ? i : maxBufferSize);85 }86 const firstBufferMessage = parseInt(log.logs[0].message, 10);87 firstBufferMessage.should.be.equal(logRecordsCount - log.logs.length + 1);88 const lastBufferMessage = parseInt(log.logs[log.logs.length - 1].message, 10);89 lastBufferMessage.should.be.equal(logRecordsCount);90 });91 describe('real device logging', function () {92 function getLogger (realDeviceLogger, udid = '1234') {93 let log = new IOSLog({sim, udid, realDeviceLogger});94 log.finishStartingLogCapture = async function () {};95 return log;96 }97 describe('idevicesyslog', function () {98 describe('system version', function () {99 let whichStub;100 afterEach(function () {101 whichStub.restore();102 });103 it('should use system idevicesyslog if no path specified', async function () {104 whichStub = sinon.stub(fs, 'which').returns('/path/to/idevicesyslog');105 let log = getLogger('idevicesyslog');106 await log.startCapture();107 log.proc.cmd.should.eql('idevicesyslog');108 });109 it('should fail if no system idevicesyslog found', async function () {110 whichStub = sinon.stub(fs, 'which').throws(new Error('ENOENT'));111 let log = getLogger('idevicesyslog');112 await log.startCapture().should.eventually.be.rejectedWith(/Unable to find system idevicesyslog/);113 });114 });115 describe('specific path', function () {116 let existstub;117 afterEach(function () {118 existstub.restore();119 });120 it('should use specified idevicesyslog if given', async function () {121 existstub = sinon.stub(fs, 'exists').returns(true);122 let log = getLogger('/path/to/my/idevicesyslog');123 await log.startCapture();124 log.proc.cmd.should.eql('/path/to/my/idevicesyslog');125 });126 it('should fail if specified idevicesyslog is not found', async function () {127 existstub = sinon.stub(fs, 'exists').returns(false);128 let log = getLogger('/path/to/my/idevicesyslog');129 await log.startCapture().should.eventually.be.rejectedWith(/Unable to find idevicesyslog from 'realDeviceLogger' capability/);130 });131 });132 describe('cache idevicesyslog instances', function () {133 let log, logForSameDevice, logForOtherDevice;134 let whichStub;135 before (function () {136 whichStub = sinon.stub(fs, 'which').returns(true);137 IOSLog.cachedIDeviceSysLogs = {};138 });139 after (function () {140 whichStub.restore();141 });142 beforeEach(async function () {143 // Create two loggers for udid 1234 and one for udid 4567144 log = getLogger('idevicesyslog');145 logForSameDevice = getLogger('idevicesyslog');146 logForOtherDevice = getLogger('idevicesyslog', '4567');147 // Start capturing148 await log.startCapture();149 await logForSameDevice.startCapture();150 await logForOtherDevice.startCapture();151 });152 afterEach(async function () {153 await log.stopCapture();154 await logForSameDevice.stopCapture();155 await logForOtherDevice.stopCapture();156 });157 it('should use same subprocess for same device', function () {158 logForSameDevice.proc.should.equal(log.proc);159 logForOtherDevice.proc.should.not.equal(log.proc);160 });161 it('should cache idevicesyslog subprocesses per device', function () {162 IOSLog.cachedIDeviceSysLogs[log.subprocessId].proc.should.equal(log.proc);163 IOSLog.cachedIDeviceSysLogs[log.subprocessId].proc.should.equal(logForSameDevice.proc);164 IOSLog.cachedIDeviceSysLogs[log.subprocessId].count.should.equal(2);165 IOSLog.cachedIDeviceSysLogs[logForOtherDevice.subprocessId].proc.should.equal(logForOtherDevice.proc);166 IOSLog.cachedIDeviceSysLogs[logForOtherDevice.subprocessId].count.should.equal(1);167 });168 it('should delete cached subprocess for a device when its only logger has stopped', async function () {169 IOSLog.cachedIDeviceSysLogs[logForOtherDevice.subprocessId].should.exist;170 await logForOtherDevice.stopCapture();171 should.not.exist(IOSLog.cachedIDeviceSysLogs[logForOtherDevice.subprocessId]);172 });173 it('should delete cached subprocesses for a device when all loggers per stopped', async function () {174 IOSLog.cachedIDeviceSysLogs[log.subprocessId].should.exist;175 await log.stopCapture();176 IOSLog.cachedIDeviceSysLogs[log.subprocessId].should.exist;177 await logForSameDevice.stopCapture();178 should.not.exist(IOSLog.cachedIDeviceSysLogs[log.subprocessId]);179 await logForOtherDevice.stopCapture();180 IOSLog.cachedIDeviceSysLogs.should.eql({});181 });182 it('should not stop idevicesyslog if another one is open for the same device', async function () {183 const killSubProcSpy = sinon.spy(log, 'killLogSubProcess');184 const otherKillSubProcSpy = sinon.spy(logForSameDevice, 'killLogSubProcess');185 await log.stopCapture();186 await logForSameDevice.stopCapture();187 killSubProcSpy.notCalled.should.be.true;188 otherKillSubProcSpy.calledOnce.should.be.true;189 });190 it('should kill the cache if "exit" event was called on the process', async function () {191 IOSLog.cachedIDeviceSysLogs[log.subprocessId].proc.should.equal(log.proc);192 log.proc.emit('exit');193 should.not.exist(IOSLog.cachedIDeviceSysLogs[log.subprocessId]);194 await log.startCapture();195 await logForSameDevice.startCapture();196 IOSLog.cachedIDeviceSysLogs[log.subprocessId].proc.should.equal(log.proc);197 });198 });199 });200 describe('deviceconsole', function () {...
dragcapture.js
Source:dragcapture.js
1/*2 * This file is part of Toolkit.3 *4 * Toolkit is free software; you can redistribute it and/or5 * modify it under the terms of the GNU General Public6 * License as published by the Free Software Foundation; either7 * version 3 of the License, or (at your option) any later version.8 *9 * Toolkit is distributed in the hope that it will be useful,10 * but WITHOUT ANY WARRANTY; without even the implied warranty of11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU12 * Lesser General Public License for more details.13 *14 * You should have received a copy of the GNU General15 * Public License along with this program; if not, write to the16 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,17 * Boston, MA 02110-1301 USA18 */19"use strict";20(function(w, TK){21var document = window.document;22/* this has no global symbol */23function CaptureState(start) {24 this.start = start;25 this.prev = start;26 this.current = start;27}28CaptureState.prototype = {29 /* distance from start */30 distance: function() {31 var v = this.vdistance();32 return Math.sqrt(v[0]*v[0] + v[1]*v[1]);33 },34 set_current: function(ev) {35 this.prev = this.current;36 this.current = ev;37 return true;38 },39 vdistance: function() {40 var start = this.start;41 var current = this.current;42 return [ current.clientX - start.clientX, current.clientY - start.clientY ];43 },44 prev_distance: function() {45 var prev = this.prev;46 var current = this.current;47 return [ current.clientX - prev.clientX, current.clientY - prev.clientY ];48 },49};50/* general api */51function startcapture(state) {52 /* do nothing, let other handlers be called */53 if (this.drag_state) return;54 55 /**56 * Capturing started.57 * 58 * @event TK.DragCapture#startcapture59 * 60 * @param {object} state - An internal state object.61 * @param {DOMEvent} start - The event object of the initial event.62 */63 var v = this.fire_event("startcapture", state, state.start);64 if (v === true) {65 /* we capture this event */66 this.drag_state = state;67 this.set("state", true);68 }69 return v;70}71function movecapture(ev) {72 var d = this.drag_state;73 74 /**75 * A movement was captured.76 * 77 * @event TK.DragCapture#movecapture78 * 79 * @param {DOMEvent} event - The event object of the current move event.80 */81 82 if (!d.set_current(ev) || this.fire_event("movecapture", d) === false) {83 stopcapture.call(this, ev);84 return false;85 }86}87function stopcapture(ev) {88 var s = this.drag_state;89 if (s === null) return;90 91 /**92 * Capturing stopped.93 * 94 * @event TK.DragCapture#stopcapture95 * 96 * @param {object} state - An internal state object.97 * @param {DOMEvent} event - The event object of the current event.98 */99 100 this.fire_event("stopcapture", s, ev);101 this.set("state", false);102 s.destroy();103 this.drag_state = null;104}105/* mouse handling */106function MouseCaptureState(start) {107 this.__mouseup = null;108 this.__mousemove = null;109 CaptureState.call(this, start);110}111MouseCaptureState.prototype = Object.assign(Object.create(CaptureState.prototype), {112 set_current: function(ev) {113 var start = this.start;114 /* If the buttons have changed, we assume that the capture has ended */115 if (!this.is_dragged_by(ev)) return false;116 return CaptureState.prototype.set_current.call(this, ev);117 },118 init: function(widget) {119 this.__mouseup = mouseup.bind(widget);120 this.__mousemove = mousemove.bind(widget);121 document.addEventListener("mousemove", this.__mousemove);122 document.addEventListener("mouseup", this.__mouseup);123 },124 destroy: function() {125 document.removeEventListener("mousemove", this.__mousemove);126 document.removeEventListener("mouseup", this.__mouseup);127 this.__mouseup = null;128 this.__mousemove = null;129 },130 is_dragged_by: function(ev) {131 var start = this.start;132 if (start.buttons !== ev.buttons || start.which !== ev.which) return false;133 return true;134 },135});136function mousedown(ev) {137 var s = new MouseCaptureState(ev);138 var v = startcapture.call(this, s);139 /* ignore this event */140 if (v === void(0)) return;141 ev.stopPropagation();142 ev.preventDefault();143 /* we did capture */144 if (v === true) s.init(this);145 return false;146}147function mousemove(ev) {148 movecapture.call(this, ev);149}150function mouseup(ev) {151 stopcapture.call(this, ev);152}153/* touch handling */154/*155 * Old Safari versions will keep the same Touch objects for the full lifetime156 * and simply update the coordinates, etc. This is a bug, which we work around by157 * cloning the information we need.158 */159function clone_touch(t) {160 return {161 clientX: t.clientX,162 clientY: t.clientY,163 identifier: t.identifier,164 };165}166function TouchCaptureState(start) {167 CaptureState.call(this, start);168 var touch = start.changedTouches.item(0);169 touch = clone_touch(touch);170 this.stouch = touch;171 this.ptouch = touch;172 this.ctouch = touch;173}174TouchCaptureState.prototype = Object.assign(Object.create(CaptureState.prototype), {175 find_touch: function(ev) {176 var id = this.stouch.identifier;177 var touches = ev.changedTouches;178 var touch;179 for (var i = 0; i < touches.length; i++) {180 touch = touches.item(i);181 if (touch.identifier === id) return touch;182 }183 return null;184 },185 set_current: function(ev) {186 var touch = clone_touch(this.find_touch(ev));187 this.ptouch = this.ctouch;188 this.ctouch = touch;189 return CaptureState.prototype.set_current.call(this, ev);190 },191 vdistance: function() {192 var start = this.stouch;193 var current = this.ctouch;194 return [ current.clientX - start.clientX, current.clientY - start.clientY ];195 },196 prev_distance: function() {197 var prev = this.ptouch;198 var current = this.ctouch;199 return [ current.clientX - prev.clientX, current.clientY - prev.clientY ];200 },201 destroy: function() {202 },203 is_dragged_by: function(ev) {204 return this.find_touch(ev) !== null;205 },206});207function touchstart(ev) {208 /* if cancelable is false, this is an async touchstart, which happens209 * during scrolling */210 if (!ev.cancelable) return;211 /* the startcapture event handler has return false. we do not handle this212 * pointer */213 var v = startcapture.call(this, new TouchCaptureState(ev));214 if (v === void(0)) return;215 ev.preventDefault();216 ev.stopPropagation();217 return false;218}219function touchmove(ev) {220 if (!this.drag_state) return;221 /* we are scrolling, ignore the event */222 if (!ev.cancelable) return;223 /* if we cannot find the right touch, some other touchpoint224 * triggered this event and we do not care about that */225 if (!this.drag_state.find_touch(ev)) return;226 /* if movecapture returns false, the capture has ended */227 if (movecapture.call(this, ev) !== false) {228 ev.preventDefault();229 ev.stopPropagation();230 return false;231 }232}233function touchend(ev) {234 var s;235 if (!ev.cancelable) return;236 s = this.drag_state;237 /* either we are not dragging or it is another touch point */238 if (!s || !s.find_touch(ev)) return;239 stopcapture.call(this, ev);240 ev.stopPropagation();241 ev.preventDefault();242 return false;243}244function touchcancel(ev) {245 return touchend.call(this, ev);246}247var dummy = function() {};248function get_parents(e) {249 var ret = [];250 if (Array.isArray(e)) e.map(function(e) { e = e.parentNode; if (e) ret.push(e); });251 else if (e = e.parentNode) ret.push(e);252 return ret;253}254var static_events = {255 set_node: function(value) {256 this.delegate_events(value);257 },258 contextmenu: function() { return false; },259 delegated: [260 function(element, old_element) {261 /* cancel the current capture */262 if (old_element) stopcapture.call(this);263 },264 function(elem, old) {265 /* NOTE: this works around a bug in chrome (#673102) */266 if (old) TK.remove_event_listener(get_parents(old), "touchstart", dummy);267 if (elem) TK.add_event_listener(get_parents(elem), "touchstart", dummy);268 }269 ],270 touchstart: touchstart,271 touchmove: touchmove,272 touchend: touchend,273 touchcancel: touchcancel,274 mousedown: mousedown,275};276TK.DragCapture = TK.class({277 278 /**279 * TK.DragCapture is a low-level class for tracking drag events on280 * both, touch and mouse events. It can be used for implementing drag'n'drop281 * functionality as well as dragging the value of e.g. {@link TK.Fader} or282 * {@link TK.Knob}. {@link TK.DragValue} derives from TK.DragCapture.283 * 284 * @extends TK.Module285 *286 * @param {Object} widget - The parent widget making use of DragValue.287 * @param {Object} [options={ }] - An object containing initial options.288 * 289 * @property {HTMLElement} [options.node] - The DOM element receiving the drag events. If not set the widgets element is used.290 * 291 * @class TK.DragCapture292 */293 294 Extends: TK.Module,295 _class: "DragCapture",296 _options: {297 node: "object",298 state: "boolean", /* internal, undocumented */299 },300 options: {301 state: false,302 },303 static_events: static_events,304 initialize: function(widget, O) {305 TK.Module.prototype.initialize.call(this, widget, O);306 this.drag_state = null;307 if (O.node === void(0)) O.node = widget.element;308 this.set("node", O.node);309 },310 destroy: function() {311 TK.Base.prototype.destroy.call(this);312 stopcapture.call(this);313 },314 cancel_drag: stopcapture,315 dragging: function() {316 return this.options.state;317 },318 state: function() {319 return this.drag_state;320 },321 is_dragged_by: function(ev) {322 return this.drag_state !== null && this.drag_state.is_dragged_by(ev);323 },324});...
teamview.js
Source:teamview.js
...45 stopcapture.addEventListener("click", function(evt) {46 const chatboxid = this.getAttribute("chatboxid");47 const userid = this.getAttribute("userid");48 const teamviewscreen = document.getElementById("teamviewscreenID"+chatboxid+"-"+userid);49 tvwcntrl.twcontrol.stopCapture(teamviewscreen);50 }, false);51 teamviewscreenbean.appendChild(teamviewscreen);52 teamviewcontrol.appendChild(startcapture);53 teamviewcontrol.appendChild(stopcapture);54 teamviewcontrol.appendChild(teamviewminimize);55 teamviewcontrol.appendChild(teamviewmaximize);56 teamviewcontrol.appendChild(teamviewclose);57 teamviewcontrolbean.appendChild(teamviewcontrol);58 teamviewwindow.appendChild(teamviewcontrolbean);59 teamviewwindow.appendChild(teamviewscreenbean);60 document.body.prepend(teamviewwindow);61 },62 getreceivedinterface: function (chatboxid, userid) {63 const teamviewwindow = dmt.domtool.creatediv("teamviewwindow", "teamviewwindowID"+chatboxid+"-"+userid);...
buttons_states.js
Source:buttons_states.js
...66 $(SELECTORS.PLAYCAPTURE).prop('disabled', true);67 $(SELECTORS.STEPCAPTURE).prop('disabled', true);68 });69 $(SELECTORS.STOPCAPTURE).click(function() {70 _model.saveText('recording', 'rec', JSON.stringify(_model.stopCapture()));71 $(SELECTORS.STARTCAPTURE).prop('disabled', false);72 $(SELECTORS.STOPCAPTURE).prop('disabled', true);73 $(SELECTORS.RESETCAPTURE).prop('disabled', false);74 });75 $(SELECTORS.RESETCAPTURE).click(function() {76 _model.resetCapture();77 $(SELECTORS.STARTCAPTURE).prop('disabled', false);78 $(SELECTORS.STOPCAPTURE).prop('disabled', true);79 $(SELECTORS.RESETCAPTURE).prop('disabled', true);80 $(SELECTORS.PLAYCAPTURE).prop('disabled', false);81 });82 $(SELECTORS.PLAYCAPTURE).click(function() {83 _model.readText(null, '.rec', function(content) {84 _model.playCapture(JSON.parse(content), function() {...
App.js
Source:App.js
...10 this.webcam = webcam;11 };12 capture = () => {13 const imageSrc = this.webcam.getScreenshot();14 this.props.stopCapture(imageSrc);15 };16 render() {17 if (!this.props.active) {18 return '';19 }20 return (21 <div>22 <Webcam audio={false} height={350} ref={this.setRef} screenshotFormat="image/jpeg" width={350} />23 <button onClick={this.capture}>Capture photo</button>24 </div>25 );26 }27}28class App extends Component {29 constructor(props) {30 super(props);31 this.client = props.client;32 this.db = this.client.service('mongodb', 'mongodb-atlas').db('security-system');33 this.state = { doCapture: false, images: [], settings: { camera_url: '', unlock_url: '' } };34 this.startCapture = this.startCapture.bind(this);35 this.stopCapture = this.stopCapture.bind(this);36 this.loadImages = this.loadImages.bind(this);37 this.removeImage = this.removeImage.bind(this);38 this.setCameraURL = this.setCameraURL.bind(this);39 this.setUnlockURL = this.setUnlockURL.bind(this);40 this.loadImages();41 this.loadSettings();42 }43 startCapture() {44 this.setState({ doCapture: true });45 }46 stopCapture(imageSrc) {47 this.setState({ doCapture: false });48 this.db49 .collection('images')50 .insertOne({51 owner_id: this.client.authedId(),52 image: imageSrc,53 active: true,54 })55 .then(this.loadImages);56 }57 loadImages() {58 this.db59 .collection('images')60 .find({ active: true })...
useRecorder.js
Source:useRecorder.js
1import { useState, useRef, useEffect, useCallback } from "preact/hooks";2import VideoStreamMerger from "video-stream-merger";3/**4 * Record screen to capture output.5 * @param {Object} constraints Constraint for display media6 * @returns {MediaStream}7 */8async function captureScreen(constraints) {9 return await navigator.mediaDevices.getDisplayMedia(constraints);10}11/**12 * Record camera to capture webcam output.13 * @returns {MediaStream}14 */15async function captureCamera(constraints) {16 return await navigator.mediaDevices.getUserMedia(constraints);17}18/** @class Encapsulating MediaRecorder */19function RecordStream(stream) {20 /**21 * MediaRecorder object22 * @member {MediaRecorder}23 * @memberof {RecordStream}24 * @instance25 */26 this.recorder = new MediaRecorder(stream, {27 mimeType: "video/webm",28 });29 this.chunks = [];30 this.start = () => {31 this.recorder.start();32 this.recorder.addEventListener("dataavailable", (event) => {33 const data = event.data;34 if (data && data.size > 0) {35 this.chunks.push(data);36 }37 });38 };39 this.getBlobs = async () => {40 return new Promise((resolve) => {41 setTimeout(() => {42 resolve(new Blob(this.chunks, { type: "video/webm" }));43 }, 0);44 });45 };46 this.stop = async () => {47 if (this.recorder.state != "inactive") {48 this.recorder.stop();49 }50 return this.getBlobs();51 };52}53/**54 * Merge streams together and return result55 * @param {MediaStream} camera camera stream56 * @param {MediaStream} screen screen stream57 * @param {MediaStreamConstraints} constraints placed on the stream58 */59async function mergeCameraScreen(camera, screen, constraints) {60 const merger = VideoStreamMerger({61 width: window.screen.width,62 height: window.screen.height,63 });64 merger.addStream(screen, {65 x: 0,66 y: 0,67 width: merger.width,68 height: merger.height,69 mute: true,70 });71 merger.addStream(camera, {72 x: merger.width - 320,73 y: merger.height - 240,74 width: 320,75 height: 240,76 mute: constraints.audio,77 });78 merger.start();79 return merger.result;80}81/**82 * A recorder custom hook83 * @param {Object} options84 * @param {useRecorder~onFinish} options.onFinish callback called when recording completes.85 */86function useRecorder({ onFinish }) {87 const [error, setError] = useState(null);88 const [isRecording, setIsRecording] = useState(false);89 const [stream, setStream] = useState(null);90 const mediaRecorder = useRef(null);91 const cameraStream = useRef(null);92 const screenStream = useRef(null);93 const stopCapture = useCallback(async () => {94 [cameraStream.current, screenStream.current, stream]95 .filter(Boolean)96 .map((stream) => {97 stream.getTracks().forEach((track) => track.stop());98 stream.removeEventListener("inactive", stopCapture);99 stream.removeEventListener("ended", stopCapture);100 });101 setStream(null);102 const recording = await mediaRecorder.current.stop();103 onFinish(recording);104 setIsRecording(false);105 }, [stream, onFinish]);106 useEffect(() => {107 if (stream) {108 /* When sharing a screen, users get an exclusive stop sharing screen button and get to use it instead of the one provided on our interface. */109 screenStream.current &&110 screenStream.current.addEventListener("inactive", stopCapture);111 stream.addEventListener("inactive", stopCapture);112 stream.addEventListener("ended", stopCapture);113 }114 return () => {115 if (stream) {116 screenStream.current &&117 screenStream.current.removeEventListener("inactive", stopCapture);118 stream.removeEventListener("inactive", stopCapture);119 stream.removeEventListener("ended", stopCapture);120 }121 };122 }, [stream, stopCapture]);123 /**124 * Start recording function125 */126 const startRecording = async ({ type, constraints }) => {127 try {128 screenStream.current = type.screen && (await captureScreen(constraints));129 cameraStream.current = type.camera && (await captureCamera(constraints));130 setIsRecording(true);131 const stream = await (() => {132 if (screenStream.current && cameraStream.current) {133 return mergeCameraScreen(134 cameraStream.current,135 screenStream.current,136 constraints137 );138 }139 return cameraStream.current || screenStream.current;140 })();141 setStream(stream);142 mediaRecorder.current = new RecordStream(stream);143 mediaRecorder.current.start();144 } catch (err) {145 setError(err);146 console.error(err);147 setIsRecording(false);148 }149 };150 return {151 error,152 start: startRecording,153 isRecording,154 stream,155 stop: stopCapture,156 };157}158/**159 * @callback useRecorder~onFinish160 * @param {Blob} blob161 */...
main.js
Source:main.js
...61 }62}63function startTimed() {64 if (timerInterval) {65 stopCapture();66 return;67 }68 const dur = document.querySelector('#duration').value;69 startCapture();70 timerInterval = setTimeout(stopCapture, dur*1000);71}72function clearScreen() {73 clear();74}75function startCapture() {76 // startScreen = false;77 capturing = true;78 document.querySelector('#start').innerHTML = 'Stop';79 document.querySelector('#settings').style.display = 'none';80}81function stopCapture() {82 // startScreen = true;83 capturing = false;84 document.querySelector('#start').innerHTML = 'Capture';85 document.querySelector('#settings').style.display = 'inline';86 if (timerInterval) {87 clearTimeout(timerInterval);88 timerInterval = null;89 }90}91function save() {92 save('test', 'png');93}94function keyPressed() {95 switch (key) {96 case ' ':97 startCapture();98 break;99 case 'c':100 clearScreen();101 break;102 }103}104function keyReleased() {105 if (key === ' ') {106 stopCapture();107 }108}109// function mousePressed(){110 // console.log('mousepressed');111 // if (startScreen) {112 // startScreen = false;113 // }114 // // clear();115 // // background(0);116// }117// function mouseReleased() {118 // startScreen = true;...
streamer.js
Source:streamer.js
...29 // get the active track of the stream30 const track = stream.getVideoTracks()[0];31 // listen for track ending, fires when user aborts through browser32 track.onended = function (event) {33 stopCapture();34 };35 // wait for video ready36 videoElem.addEventListener('loadedmetadata', (e) => {37 window.setTimeout(() => (38 onCapabilitiesReady(track.getSettings())39 ), 500);40 });41 } catch (err) {42 stopCapture();43 console.error("Error: " + err);44 }45 }46 function onCapabilitiesReady(settings) {47 // extract real width/height48 streamImageWidth = settings.width;49 streamImageHeight = settings.height;50 // start screenshotTimer51 updateScrTimer(false);52 // we are sending53 $("#btn_streamer_icon").addClass("text-danger");54 }55 function stopCapture(evt) {56 streamActive = false;57 $("#btn_streamer_icon").removeClass("text-danger");58 updateScrTimer(true);59 // sometimes it's null on abort60 if (videoElem.srcObject) {61 let tracks = videoElem.srcObject.getTracks();62 tracks.forEach(track => track.stop());63 videoElem.srcObject = null;64 }65 requestPriorityClear(1);66 }67 function takePicture() {68 var context = canvasElem.getContext('2d');69 canvasElem.width = streamImageWidth;70 canvasElem.height = streamImageHeight;71 context.drawImage(videoElem, 0, 0, streamImageWidth, streamImageHeight);72 var data = canvasElem.toDataURL('image/png').split(",")[1];73 requestSetImage(data, -1, "Streaming");74 }75 // start or update screenshot timer76 function updateScrTimer(stop) {77 clearInterval(screenshotTimer)78 if (stop === false) {79 screenshotTimer = setInterval(() => (80 takePicture()81 ), screenshotIntervalTimeMs);82 }83 }84 $("#btn_streamer").off().on("click", function (e) {85 if (!$("#btn_streamer_icon").hasClass("text-danger") && !streamActive) {86 startCapture();87 } else {88 stopCapture();89 }90 });91 $(window.hyperion).on("stopBrowerScreenCapture", function (event) {92 if (streamActive) {93 stopCapture();94 }95 });...
Using AI Code Generation
1var webdriver = require('selenium-webdriver'),2 until = webdriver.until;3var driver = new webdriver.Builder()4 .forBrowser('selenium')5 .build();6driver.findElement(By.name('q')).sendKeys('webdriver');7driver.findElement(By.name('btnG')).click();8driver.wait(until.titleIs('webdriver - Google Search'), 1000);9driver.quit();10driver.stopCapture().then(function (res) {11 console.log(res);12});13driver.stopCapture().then(function (res) {14 console.log(res);15});16[debug] [BaseDriver] Event 'newSessionStarted' logged at 1566567325596 (13:12:05 GMT+0530 (IST))17[debug] [W3C] at XCUITestDriver.executeCommand (/usr/local/lib/node_modules/appium/node_modules/appium-base-driver/lib/basedriver/driver.js:335:13)18driver.stopRecordingScreen().then(function (res) {19 console.log(res);20});
Using AI Code Generation
1const wd = require('wd');2const chai = require('chai');3const chaiAsPromised = require('chai-as-promised');4chai.use(chaiAsPromised);5const should = chai.should();6driver.init({7});8driver.sleep(5000).then(() => {9 return driver.stopCapture();10});11driver.quit();
Using AI Code Generation
1var ffmpeg = require('fluent-ffmpeg');2var command = ffmpeg('video.mp4');3 .output('video.webm')4 .on('end', function() {5 console.log('file has been converted succesfully');6 })7 .on('error', function(err) {8 console.log('an error happened: ' + err.message);9 })10 .run();11 at exports._errnoException (util.js:1022:11)12 at Process.ChildProcess._handle.onexit (internal/child_process.js:190:19)13 at onErrorNT (internal/child_process.js:372:16)14 at _combinedTickCallback (internal/process/next_tick.js:138:11)15 at process._tickCallback (internal/process/next_tick.js:180:9)16 at Module.runMain (module.js:695:11)17 at run (bootstrap_node.js:204:7)18 at startup (bootstrap_node.js:625:9)19var ffmpeg = require('fluent-ffmpeg');20var command = ffmpeg('video.mp4');21 .output('video.webm')22 .on('end', function() {23 console.log('file has been converted succesfully');24 })25 .on('error',
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var desiredCaps = {4};5driver.init(desiredCaps)6 .then(function () {7 return driver.setImplicitWaitTimeout(30000);8 })9 .then(function () {10 return driver.execute('mobile: stopCapture');11 })12 .then(function () {13 console.log("stopCapture method executed");14 })15 .catch(function (err) {16 console.log(err);17 });18driver.execute('mobile: stopCapture');19driver.execute('mobile: stopCapture', ['mobile: stopCapture']);20driver.execute('mobile: stopCapture', {});21driver.execute('mobile: stopCapture');22driver.execute('mobile: stopCapture', ['mobile: stopCapture']);23driver.execute('mobile: stopCapture', {});24driver.execute('mobile: stopCapture');25driver.execute('mobile: stopCapture', ['mobile: stopCapture']);26driver.execute('mobile: stopCapture', {});27driver.execute('mobile: stopCapture');
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!!