How to record desktop screen video using recordRTC node module of selected screen area? - node.js

I am working on desktop application using NW.js wherein required to record selected area of desktop screen. currently using RecordRTC node module for recording video. but this gives me full screen video recording. please assist if there any other package to achieve this across platforms (win/linux/mac).

Please check this demo (name as "Record Cropped Screen using RecordRTC"):
https://www.webrtc-experiment.com/RecordRTC/simple-demos/record-cropped-screen.html
Here is complete HTML code (try on any HTTPs page or localhost or node-webkit):
<button id="btn-start-recording">Start Recording</button>
<button id="btn-stop-recording" style="display: none;">Stop Recording</button>
<br><hr>
<div id="edit-panel" style="border-bottom: 1px solid;">
<div>
<label for="x">X</label>
<input type="number" name="x" id="x" value="0" />
</div>
<div>
<label for="y">Y</label>
<input type="number" name="y" id="y" value="0" />
</div>
<div>
<label for="w">Width (-1 = Full size)</label>
<input type="number" name="w" id="w" value="-1" />
</div>
<div>
<label for="h">Height (-1 = Full size)</label>
<input type="number" name="h" id="h" value="-1" />
</div>
<button id="update" style="display: none;">Update X-Y Width-Height Coordinates</button>
<canvas></canvas>
</div>
<video id="mediaElement"></video>
<script src="https://cdn.webrtc-experiment.com/RecordRTC.js"></script>
<script src="https://cdn.WebRTC-Experiment.com/getScreenId.js"></script>
<script>
// this script tag is taken from: https://github.com/andersevenrud/webrtc-screenshare-crop-demo
var CROP_X = 10;
var CROP_Y = 20;
var CROP_W = 320; // default width
var CROP_H = 240; // default height
var VIDEO_WIDTH = 0;
var VIDEO_HEIGHT = 0;
var MAX_VIDEO_WIDTH = 1920;
var MAX_VIDEO_HEIGHT = 1080;
var _canvas;
var _context;
var htmlCanvasElement = document.querySelector('canvas');
// Form elements
document.getElementById("x").value = CROP_X;
document.getElementById("y").value = CROP_Y;
document.getElementById("w").value = CROP_W;
document.getElementById("h").value = CROP_H;
document.getElementById("update").onclick = function() {
var x = document.getElementById("x").value << 0;
var y = document.getElementById("y").value << 0;
var w = document.getElementById("w").value << 0;
var h = document.getElementById("h").value << 0;
if (x >= 0) {
CROP_X = x;
}
if (y >= 0) {
CROP_Y = y;
}
CROP_W = w || 0;
CROP_H = h || 0;
};
_context = htmlCanvasElement.getContext('2d');
/**
* Crops a video frame and shows it to the user
*/
function CropFrame(ev, stream, video, callback) {
callback = callback || function() {};
_canvas = htmlCanvasElement;
if (CROP_X < 0) {
CROP_X = 0;
}
if (CROP_Y < 0) {
CROP_Y = 0;
}
if (CROP_W <= 0) {
CROP_W = VIDEO_WIDTH;
}
if (CROP_H <= 0) {
CROP_H = VIDEO_HEIGHT;
}
if (CROP_W > MAX_VIDEO_WIDTH) {
CROP_W = MAX_VIDEO_WIDTH;
}
if (CROP_H > MAX_VIDEO_HEIGHT) {
CROP_W = MAX_VIDEO_HEIGHT;
}
_canvas.width = CROP_W;
_canvas.height = CROP_H;
_context.drawImage(video, CROP_X, CROP_Y, CROP_W, CROP_H, 0, 0, CROP_W, CROP_H);
// We need to scale down the image or else we get HTTP 414 Errors
// Also we scale down because of RTC message length restriction
var scanvas = document.createElement('canvas');
scanvas.width = _canvas.width;
scanvas.height = _canvas.height;
var wRatio = _canvas.width / 320;
var hRatio = _canvas.height / 240;
var maxRatio = Math.max(wRatio, hRatio);
if (maxRatio > 1) {
scanvas.width = _canvas.width / maxRatio;
scanvas.height = _canvas.height / maxRatio;
}
scanvas.getContext('2d').drawImage(_canvas, 0, 0, scanvas.width, scanvas.height);
callback(scanvas.toDataURL("image/jpeg"));
}
var recorder;
function captureScreen(cb) {
getScreenId(function(error, sourceId, screen_constraints) {
navigator.getUserMedia(screen_constraints, cb, function(error) {
console.error('getScreenId error', error);
alert('Failed to capture your screen. Please check Chrome console logs for further information.');
});
});
}
var mediaElement = document.querySelector('#mediaElement');
document.querySelector('#btn-start-recording').onclick = function() {
document.querySelector('#btn-start-recording').style.display = 'none';
navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia;
captureScreen(function(screen) {
var inited = false;
mediaElement.ontimeupdate = function(ev) {
if (!inited) {
VIDEO_WIDTH = mediaElement.offsetWidth;
VIDEO_HEIGHT = mediaElement.offsetHeight;
mediaElement.style.display = 'none';
document.querySelector('#edit-panel').style.display = 'block';
inited = true;
}
CropFrame(ev, screen, mediaElement);
};
mediaElement.src = URL.createObjectURL(screen);
mediaElement.play();
mediaElement.screen = screen;
addStreamStopListener(screen, function() {
document.querySelector('#btn-stop-recording').onclick();
});
// RecordRTC goes here
var captureStream = htmlCanvasElement.captureStream();
recorder = RecordRTC(captureStream, {
type: 'video'
});
recorder.startRecording();
document.querySelector('#btn-stop-recording').style.display = 'inline';
});
};
document.querySelector('#btn-stop-recording').onclick = function() {
document.querySelector('#btn-stop-recording').style.display = 'none';
recorder.stopRecording(function() {
var blob = recorder.getBlob();
document.querySelector('#edit-panel').style.display = 'none';
mediaElement.style.display = 'block';
mediaElement.src = URL.createObjectURL(blob);
mediaElement.play();
if (mediaElement.screen && mediaElement.screen.getVideoTracks) {
mediaElement.screen.stop();
mediaElement.screen = null;
}
document.querySelector('#btn-start-recording').style.display = 'inline';
});
};
function addStreamStopListener(stream, callback) {
var streamEndedEvent = 'ended';
if ('oninactive' in stream) {
streamEndedEvent = 'inactive';
}
stream.addEventListener(streamEndedEvent, function() {
callback();
callback = function() {};
}, false);
stream.getAudioTracks().forEach(function(track) {
track.addEventListener(streamEndedEvent, function() {
callback();
callback = function() {};
}, false);
});
stream.getVideoTracks().forEach(function(track) {
track.addEventListener(streamEndedEvent, function() {
callback();
callback = function() {};
}, false);
});
}
function querySelectorAll(selector) {
return Array.prototype.slice.call(document.querySelectorAll(selector));
}
querySelectorAll('input').forEach(function(input) {
input.onkeyup = input.oninput = function() {
if (!document.querySelector('#update').onclick) return;
document.querySelector('#update').onclick();
};
});
</script>

Related

Clicking Submit button doesn't respond to selenium vba

I have a form that I fill with some data and everything is OK till I tried to click on Submit button. It doesn't respond at all
Here's the outHTML of the element
<input type="submit" class="btn btn-primary commandButton" value="إرسال الطلــب" id="cmdSubmit">
I tried these lines
.ExecuteScript "arguments[0].click();", .FindElementByCss("#cmdSubmit")
I even tried byID and byXPATH and nothing worked with the element
While inspecting the webpage, I have searched for submit and I think I found related function
<script>
$('#frmExecReq').submit(function(){ // catch form submit event
if($('#selectAsed').val() <= 0){
$('#selectAsedWarninig').show();
return false;
}
if(!$.isNumeric($('#phoneNo').val())){
$('#phoneNoWarninig').show();
return false;
}
var mobileNumber = document.getElementById("phoneNo").value;
var mobileLength = mobileNumber.length;
var checkFirstNumber = mobileNumber.substring(0, 1);
if(mobileNumber ==""){
document.getElementById('phoneNoWarninig').style.display = 'inline';
document.getElementById('phoneNo').focus();
document.getElementById('phoneNo').select();
return false;
}else if( mobileLength !=8 ){
document.getElementById('phoneNoWarninig').style.display = 'inline';
document.getElementById('phoneNo').focus();
document.getElementById('phoneNo').select();
return false;
}else if(checkFirstNumber != 5 && checkFirstNumber != 6 && checkFirstNumber != 9){
document.getElementById('phoneNoWarninig').style.display = 'inline';
document.getElementById('phoneNo').focus();
document.getElementById('phoneNo').select();
return false;
}
if($('#txtReceivedSum').length){
if(!$.isNumeric($('#txtReceivedSum').val())){
$('#txtReceivedSumWarninig').show();
return false;
}
}
//////////
var trnCodeNum = document.getElementById("trnCodeNum").value;
var persType = document.getElementById("persType").value;
if( (trnCodeNum == 0815 && persType == 2) || (trnCodeNum == 0875 && persType == 2) || (trnCodeNum == 0820 && persType == 1)
|| trnCodeNum == 0810 || trnCodeNum == 0825){
var y = document.getElementById('attachments');
if ('files' in y) {
if (y.files.length == 0) {
document.getElementById('reqWarning2-1').style.display = 'inline';
//$('#sreqFile1Warning1').show();
return false;
} else {
var file = y.files[0];
if ('name' in file) {
var n = file.name;
fileExtension = n.split('.').pop();
if (!(fileExtension == "pdf")) {
$('#reqWarning2-2').show();
return false;
}
if ('size' in file) {
if (file.size > 10485762) { //10 MB
$('#reqWarning2-3').show();
return false;
}
}
}
}
}
}
///////////
var form = $('#frmExecReq')[0];
// Create an FormData object
var data = new FormData(form)
$.ajax({ // create ajax call
data: data, //get form data
//contentType: 'multipart/form-data',
processData: false,
contentType: false,
method: 'POST',
type: $(this).attr('method'), //GET or POST
url: $(this).attr('action'), // the action url
success: function(response){ // on success
$('#viewPaneChildDetails').html(response); //update DIV
$('#viewPaneChild').hide();
$('#viewPaneChildDetails').show();
}
});
return false; // cancel original event to prevent form submitting
});
</script>
When trying this line, an error occurred
.FindElementByXPath("//input[#class='btn btn-primary commandButton' and #id=='dSubmit'][#vlaue='إرسال الطلــب']").Click
To click on the element you can use either of the following locator strategies:
Using FindElementByCss:
.FindElementByCss("input.btn.btn-primary.commandButton#cmdSubmit").click
Using FindElementByXPath:
.FindElementByXPath("//input[#class='btn btn-primary commandButton' and #id='cmdSubmit']").click

How to set boolean variable to true in mongodb using function in service in nodejs

I have created a function in service using nodejs to set the boolean variable to true upon button click. But its not working.
I'm using get method in service to do the above.
// in html
<tr *ngFor="let status of bookstatus">
<td>{{status.bookname}}</td>
<td>{{status.issuedate | date:'dd/MM/yyyy'}}</td>
<td>{{status.returndate}}</td>
<td>{{status.membername}}</td>
<td>{{status.fine}}</td>
<td>{{status.status}}</td>
<td><button type="button" (click)="returnbook(status._id)">BookReturn</button></td>
</tr>
// in ts
returnbook(id: number) {
this.bookissueservice.returnbook(id).subscribe(response => {window.alert('book returned'); });
if (this.bookstatus.isreturned === true) {
this.bookstatus.status = 'returned';
var date1 = new Date(this.bookreturn);
var date2 = new Date(this.bookstatus.returndate);
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
if (diffDays !== 0) {
const res = 50;
this.fine = res + diffDays;
}
else {this.fine = 0; }
}
}
//in service
returnbook(id:number){
return this.http.get(`http://localhost:4000/api/memberdetails/${id}`).
pipe(map(response=>response));
}
//in api
router.get('/return/:id?',(req,res)=>{
var body=req.params.id;
var id=body.id;
bookissue.findById(id,(error,bookissue)=>{if(error){
console.log(error);}
/*bookissue.isreturned is the boolean variable which I'm trying to set to true on button click */
bookissue.isreturned = 1;
bookissue.save(function(error,returned){
if(error){
console.log(error);
return next(error);
}
res.json({status:true,message:'saved',data:returned});
});
});
});
If you wanna save the boolean variable to "1" use the update query.
bookissue.update({_id:id},{$set:{isreturned:true}},(error,result)=>{
if(error){
console.log(error);
return next(error);
}
console.log("result : ",result);
res.json({status:true,message:'saved',data:result});
});

how to import CSV file in angular 4 and stored data in Database?

i want to import CSV in angular 4, and store data in my database.
<input type="file" name="importCSV">
<button type="submit" class="btn btn-primary">Submit</button>
while i click on the Submit button i want to store data in my Table.
You can use the below custom function to do the needful :
private extractData(data) { // Input csv data to the function
let csvData = data;
let allTextLines = csvData.split(/\r\n|\n/);
let headers = allTextLines[0].split(',');
let lines = [];
for ( let i = 0; i < allTextLines.length; i++) {
// split content based on comma
let data = allTextLines[i].split(',');
if (data.length == headers.length) {
let tarr = [];
for ( let j = 0; j < headers.length; j++) {
tarr.push(data[j]);
}
lines.push(tarr);
}
}
console.log(lines); //The data in the form of 2 dimensional array.
}
You can read the file inside the file listener function like this:
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
var file = files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event){
var csv = event.target.result; // Content of CSV file
this.extractData(csv); //Here you can call the above function.
}
}
Inside html use below code:
<input type="file" (change)="handleFileSelect($event)"/>
here is the html code.
<input type="file" #fileImportInput name="File Upload" (change)="csvChanged($event)" id="txtFileUpload">
below is my component code
const CSVConstants = {
tokenDelimeter: ",",
isHeaderPresentFlag: true,
validateHeaderAndRecordLengthFlag: true,
valildateFileExtenstionFlag: true,
}
public csvChanged(event) {
var files = event.target.files;
if (CSVConstants.validateHeaderAndRecordLengthFlag) {
if (!this.fileUtil.isCSVFile(files[0])) {
this.utilService.showToastMsg("error", "Please import valid .csv file");
this.fileReset();
return;
}
}
var input = event.target;
var reader = new FileReader();
reader.readAsText(input.files[0]);
reader.onload = (data) => {
let csvData: any = reader.result;
let csvRecordsArray = csvData.split(/\r\n|\n/);
var headerLength = -1;
if (CSVConstants.isHeaderPresentFlag) {
let headersRow = this.fileUtil.getHeaderArray(csvRecordsArray, CSVConstants.tokenDelimeter);
headerLength = headersRow.length;
}
this.csvRecords = this.fileUtil.getDataRecordsArrayFromCSVFile(csvRecordsArray,
headerLength, CSVConstants.validateHeaderAndRecordLengthFlag, CSVConstants.tokenDelimeter);
if (this.csvRecords == null) {
//If control reached here it means csv file contains error, reset file.
this.fileReset();
}
/* Remove the file so that user can upload same one after making changes, otherwise change event
will not be called */
this.clearFile();
/* Remove the first header row */
this.csvRecords.splice(0, 1);
this.csvRecords.map((record: any) => {
this.external_contacts_arr.push({
email: record[0],
first_name: record[1],
last_name: record[2],
designation: record[3],
})
});
this.removeBlankRecords();
//document.getElementById(`${this.uniquePrefix}-other-tab`).click();
}
reader.onerror = () => {
this.utilService.showToastMsg("error", 'Unable to read ' + input.files[0]);
};
}

Mod_pagespeed do not work for make_google_analytics_async

this is my code in .htaccess file ... and I am sure mode_pagespeed works.
<IfModule pagespeed_module>
ModPagespeed on
ModPagespeedEnableFilters make_google_analytics_async
.
.
.
</IfModule>
and in html I add a java script code (I got it here)
<html>
<head>
<script type='text/javascript'>
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
GLUE_SCRIPT
var ga = document.createElement('script');
ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' :
'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
</script>
<script type="text/javascript">
try {
var pageTracker = _modpagespeed_getRewriteTracker("UA-63697801-1");
pageTracker._trackPageview();
} catch(err) {}
</script>
</head>
<body>
</body>
</html>
what's my wrong? this is not work but for another filter insert_ga works but that is not optimized.
You need to replace GLUE_SCRIPT with a function. From the Docs
where GLUE_SCRIPT is JavaScript that defines the _modpagespeed_getRewriteTracker function to return an object that maps all the methods of the synchronous API to the asynchronous API.
if you follow the example below the link provided, you can see a full implementation.
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
var _gaq = _gaq || [];
(function () {
function functionName(fn) {
var name = /\W*function\s+([\w\$]+)\(/.exec(fn);
if (!name)
return 'No name';
return name[1];
}
var nameSpace = '_gat';
var existingGat = window[nameSpace];
if (existingGat && typeof existingGat['_getTracker'] == 'function') {
return;
}
var gaqAccounts = [];
function setAccount(acct, prefix) {
if (gaqAccounts[prefix] != acct) {
gaqAccounts[prefix] = acct;
_gaq.push([prefix + '_setAccount', acct]);
}
}
window['_modpagespeed_getRewriteTracker'] = function (tracker_acct,
tracker_name) {
var prefix = tracker_name ? tracker_name + '.' : '';
function deferTrackerFunc(fn) {
return function () {
setAccount(tracker_acct, prefix);
var pushArgs = [fn];
[].push.apply(pushArgs, arguments);
_gaq.push(pushArgs);
};
}
var pageTrackerMethodNames = [
'_trackPageview',
'_trackEvent',
'_trackTrans',
'_addIgnoredOrganic',
'_addIgnoredRef',
'_addItem',
'_addOrganic',
'_addTrans',
'_clearIgnoredOrganic',
'_clearIgnoredRef',
'_clearOrganic',
'_clearXKey',
'_clearXValue',
'_cookiePathCopy',
'_deleteCustomVar',
'_link',
'_linkByPost',
'_sendXEvent',
'_setAllowAnchor',
'_setAllowHash',
'_setAllowLinker',
'_setAutoTrackOutbound',
'_setCampCIdKey',
'_setCampContentKey',
'_setCampIdKey',
'_setCampMediumKey',
'_setCampNOKey',
'_setCampNameKey',
'_setCampSourceKey',
'_setCampTermKey',
'_setCampaignCookieTimeout',
'_setCampaignTrack',
'_setClientInfo',
'_setCookiePath',
'_setCookiePersistence',
'_setCookieTimeout',
'_setCustomVar',
'_setDetectFlash',
'_setDetectTitle',
'_setDomainName',
'_setHrefExamineLimit',
'_setLocalGifPath',
'_setLocalRemoteServerMode',
'_setLocalServerMode',
'_setMaxCustomVariables',
'_setNamespace',
'_setReferrerOverride',
'_setRemoteServerMode',
'_setSampleRate',
'_setSessionCookieTimeout',
'_setSessionTimeout',
'_setTrackOutboundSubdomains',
'_setTrans',
'_setTransactionDelim',
'_setVar',
'_setVisitorCookieTimeout',
'_setXKey',
'_setXValue'
];
var pageTracker = {
_initData: function () {
},
};
for (var i = pageTrackerMethodNames.length; i--;) {
var n = pageTrackerMethodNames[i];
pageTracker[n] = deferTrackerFunc(prefix + n);
}
return pageTracker;
};
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' :
'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
try {
var pageTracker = _modpagespeed_getRewriteTracker("UA-xxxx-9");
pageTracker._trackPageview();
} catch (err) {
}

webRTC to connect two browser

For a long time I'm trying to connect the two browsers. I'm getting my voice, my own camera image only.How do I get the image and sound other browsers? The browsers connecting on the same network.
<body>
<video id="localVideo" autoplay="true" muted="true" width="400px" height="400px" ></video>
<video id="remoteVideo" autoplay="true" muted="true" width="400px" height="400px" ></video>
<div>
<button id="callButton" onclick="call();" >Call</button>
<button id="hangupButton" onclick="hangup();" disabled>Hang Up</button>
</div>
<script>
// Definitions
var localStream;
var callButton = document.getElementById("callButton");
var hangupButton = document.getElementById("hangupButton");
var localVideo = document.getElementById("localVideo");
var remoteVideo = document.getElementById("remoteVideo");
var audioVideoConstraints = {audio: true, video: true};
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL;
window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
window.RTCIceCandidate = window.mozRTCIceCandidate;
</script>
<script>
// Functions
function getUserMediaSuccessCallback(stream) {
window.stream = stream; // stream available to console
localStream = stream;
if (window.URL) {
localVideo.src = window.URL.createObjectURL(stream);
} else {
localVideo.src = stream;
}
callButton.disabled = false;
if (window.stream.getVideoTracks().length > 0) {
trace('Using video device: ' + window.stream.getVideoTracks()[0].label);
}
if (window.stream.getAudioTracks().length > 0) {
trace('Using audio device: ' + window.stream.getAudioTracks()[0].label);
}
}
function getUserMediaErrorCallback(error){
console.log("navigator.getUserMedia error: ", error);
alert("navigator.getUserMedia error: " + error);
}
function trace(text) {
console.log(text);
}
function call() {
hangupButton.disabled = false;
trace("Starting call");
var servers = null;
localPeerConnection = new RTCPeerConnection(servers);
trace("Created local peer connection object localPeerConnection");
localPeerConnection.onicecandidate = gotLocalIceCandidate;
remotePeerConnection = new RTCPeerConnection(servers);
trace("Created remote peer connection object remotePeerConnection");
remotePeerConnection.onicecandidate = gotRemoteIceCandidate;
remotePeerConnection.onaddstream = gotRemoteStream;
localPeerConnection.addStream(localStream);
trace("Added localStream to localPeerConnection");
localPeerConnection.createOffer(gotLocalDescription);
}
</script>
<script>
navigator.getUserMedia(audioVideoConstraints, getUserMediaSuccessCallback, getUserMediaErrorCallback);
Thank you very much good work :)

Resources