WebRTC issue with File transfer in production application - javascript

Hello I am developing a WebRTC based file transfer application.I have deployed the application online using Heroku. But there seems to be a problem with file transfer specifically at the the receiving end which I have been unable to figure out. The file is transferred and received successfully when done on localhost but there is a problem with file reception when done in production. The browser used is Google Chrome if that's any help.
Here is the File reception code:
function dataChannelStateChanged() {
if (dataChannel.readyState === 'open') {
console.log("Data Channel open");
dataChannel.onmessage = receiveDataChannelMessage;
}
}
function receiveDataChannel(event) {
console.log("Receiving a data channel");
dataChannel = event.channel;
dataChannel.onmessage = receiveDataChannelMessage;
}
function receiveDataChannelMessage(event) {
console.log("From DataChannel: " + event.data);
if (fileTransferring) {
//Now here is the file handling code:
fileBuffer.push(event.data);
fileSize += event.data.byteLength;
fileProgress.value = fileSize;
//Provide link to downloadable file when complete
if (fileSize === receivedFileSize) {
var received = new window.Blob(fileBuffer);
fileBuffer = [];
downloadLink.href = URL.createObjectURL(received);
downloadLink.download = receivedFileName;
downloadLink.appendChild(document.createTextNode(receivedFileName + "(" + fileSize + ") bytes"));
fileTransferring = false;
//Also put the file in the text chat area
var linkTag = document.createElement('a');
linkTag.href = URL.createObjectURL(received);
linkTag.download = receivedFileName;
linkTag.appendChild(document.createTextNode(receivedFileName));
var div = document.createElement('div');
div.className = 'message-out';
div.appendChild(linkTag);
messageHolder.appendChild(div);
}
}
else {
appendChatMessage(event.data, 'message-out');
}
}
The following image shows the problem i'm encountering when receiving the file:
Any guidance would be much appreciated.

WEBRTC is based on UDP, it means there is no guarantee that your sequence of data transfers "in order" or successfully
use "webSocket" or a simple "http request" instead.
=============
UPDATE: see the first comment

Related

File attachment is not opening-Not Allowed Error

This is my first attempt to prepare a dynamic pdf form in livecycle designer es4. In this form, there is an option to add and view attachment. As I have little experience in javascript coding, I went to the adobe forum and found a very good example here. I have done some changes in original code to run in my form. I can attach file successfully with this code. But my problem is that when I want to open file attachment in Acrobat Pro XI, it is showing below error instead of opening the file. This error is showing independent of file attachment type (e.g. .doc, .jpg, .txt and .pdf file).error image. Here is screenshot of security of Acrobat Pro XIscreenshot 1 screenshot 2 and file linkhere.
Below code is written in the form-
//Code for add button
// Get Import Name
var cName = AttachName.rawValue;
// Test for empty value
if(!/^\s*$/.test(cName))
{// Do Import
try{
var bRtn = event.target.importDataObject(cName);
if(bRtn)
{
var cDesc = AttachDesc.rawValue;
if(!/^\s*$/.test(cName))
{
var oAtt = event.target.getDataObject(cName);
oAtt.description = cDesc;
}
app.alert("File Attachment Successfully Imported",3);
}
else
app.alert("Unable to import File Attachment",0);
}catch(e){
app.alert("An Error Occured while Importing the File Attachment:\n\n" + e);
}
}
else
app.alert("Attachment name must be non-empty");
//code for populating dropdown list
this.rawValue = null;
this.clearItems();
var a = event.target.dataObjects;
if (a !== null) {
for (var i = 0; i < a.length; i++) {
this.addItem(a[i].name);
}
}
//code for open attachment button
var cName = AttachNameSel.rawValue;
//var nAction = ExportAction.rawValue;
try{
event.target.exportDataObject({cName:cName, nLaunch:2});
} catch(e) {
app.alert("An Error Occured while Exporting the File Attachment: " + cName + "\n\n" + e);
}
Any help from anyone in the community would be greatly appreciated.
Thanks
Tony

Saving a file in a UWP web context

I recently developed a universal application for Windows 10 with UWP web context (so JavaScript and HTML) and I would like to save a text file. It works well on a browser (Chrome, Firefox, Edge,...) but not in the application.
Can someone help me? :)
Thank you in advance!
Here is the code responsible for saving the text file.
function saveTextAsFile(fileName) {
var source = input.value.replace(/\n/g, "\r\n");
var fileUrl = window.URL.createObjectURL(new Blob([source], {type:"text/plain"}));
var downloadLink = createDownloadLink(fileUrl, fileName);
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);}
To download a file using a Progressive Web App as a Universal Windows Platform you can use the Windows global object with the FileSavePicker. Note that you can check to see if it exists using if (window['Windows'] != null) { ... }
// Create the picker object and set options
var savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.documentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.fileTypeChoices.insert("Plain Text", [".txt"]);
// Default file name if the user does not type one in or select a file to replace
savePicker.suggestedFileName = "New Document";
savePicker.pickSaveFileAsync().then(function (file) {
if (file) {
// Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
Windows.Storage.CachedFileManager.deferUpdates(file);
// write to file
Windows.Storage.FileIO.writeTextAsync(file, fileContents).done(function () {
// Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
// Completing updates may require Windows to ask for user input.
Windows.Storage.CachedFileManager.completeUpdatesAsync(file).done(function (updateStatus) {
if (updateStatus === Windows.Storage.Provider.FileUpdateStatus.complete) {
WinJS.log && WinJS.log("File " + file.name + " was saved.", "sample", "status");
} else {
WinJS.log && WinJS.log("File " + file.name + " couldn't be saved.", "sample", "status");
}
});
});
} else {
WinJS.log && WinJS.log("Operation cancelled.", "sample", "status");
}
});
This assumes you are downloading a text file. To download a Uint8Array use the WriteBytesAsync function on FileIO instead. Note that many of the functions on FileIO are available in JavaScript even though they are not documented for JavaScript.
Check out the FileSavePicker Class documentation for more information.

How to get downlaod progress with fetch()? [duplicate]

I am trying to download the large json data.
But it leads to Uncaught RangeError: Invalid string length.
Pls help to solve this problem,Thanks in advance.
Here is the Jsfiddle : http://jsfiddle.net/sLq3F/456/
You can use fetch(), Response.body.getReader() which returns a ReadableStream, TextDecoder(), Blob(), URL.createObjectURL().
Note, at device having limited RAM or low available disk space, after clicking Save at Save File dialog four minutes and twenty seconds 4:20 elapsed before the Save File dialog closed, followed by an additional one minute and thirty seconds 1:30 before the .crdownload extension was removed from the file at file manager GUI. During the first 4:20 period where the file is downloading to filesystem and the Save File dialog is visible the mouse pointer is movable, though the UI is temporarily unresponsive to clicks or attempts to change tabs. When the Save File dialog closes and the the file is still downloading to filesystem, having extension .crdownload the UI returns to normal functionality.
At the conclusion of the process described above the file was successfully downloaded to local filesystem having a total size of 189.8 MB (189,778,220 bytes).
<!DOCTYPE html>
<html>
<head>
<style>
code {
color:navy;
background-color:#eee;
padding:2px;
}
</style>
</head>
<body>
<button>Request File</button><br>
<progress min="0" max="189778220" value="0"></progress>
<output></output>
<br><br>
<label></label>
<script>
var url = "https://raw.githubusercontent.com/zemirco/sf-city-lots-json/master/citylots.json";
var button = document.querySelector("button");
var progress = document.querySelector("progress");
var label = document.querySelector("label");
var output = document.querySelector("output");
var request = (url) => {
label.innerHTML = `Requesting <code>${url}</code> at ${new Date()}.<br><br>`;
return fetch(url)
.then(response => response.body.getReader())
.then(reader => {
var decoder = new TextDecoder();
var json = "";
label.innerHTML += `Request successful.<br><br>Reading request body at ${new Date()}.<br><br>`;
return reader.read().then(function processData(result) {
if (result.done) {
// do stuff when `reader` is `closed`
return reader.closed.then(function() {
// return `json` string
return json;
});
};
json += decoder.decode(result.value);
output.innerHTML = ` ${json.length} of ${progress.max} bytes read`;
progress.value = json.length;
return reader.read().then(processData)
})
.then(function(data) {
var message = `Reading of <code>${url}</code> complete at ${new Date()}. <br><br>`
+ `${data.length} total bytes read. `
+ `Please allow up to 4 minutes for file to download `
+ `to filesystem after clicking <code>Save</code>.<br><br>`;
label.innerHTML += message;
var blob = new Blob([data], {
type: "application/json"
});
var file = URL.createObjectURL(blob);
var a = document.createElement("a");
a.download = "citylots.json";
a.href = file;
document.body.appendChild(a);
a.click();
var closeBlob = (e) => {
window.removeEventListener("focus", closeBlob);
blob.close();
URL.revokeObjectURL(file);
};
window.addEventListener("focus", closeBlob);
return message.replace(/<[^>]*>/g, "");
})
.catch(function(err) {
console.log("err", err)
})
});
}
var handleRequest = (e) => {
button.setAttribute("disabled", "disabled");
request(url).then(function(message) {
console.log(message);
button.removeAttribute("disabled");
})
};
button.addEventListener("click", handleRequest);
</script>
</body>
</html>
plnkr https://plnkr.co/edit/gewixzHZSKRXquZ2OVF2?p=preview
I guess you would need to loop through something in the JSON file and split it up into more manageable strings.
Tom
Do you have an example snippet the JSON file?
Do you have a server running on PHP?
if you do, I believe you must absolutely check your PHP.ini file or run a phpinfo page because php settings does limit the size of files transfer even if it isnt an external request. It could do that in other languages but I never had this problem except on PHP.
P.S. I did not see the size of the file
I think your json file is one of the "TOO BIG FOR JSON" scenarios. you know, if json file have so many records ( to be exact, based on a test, 100000 records make the browser hang and more then that failed to load in many browsers) its not recommend to use.
you can read this article for more information : HOW BIG IS TOO BIG FOR JSON?

How to solve Uncaught RangeError when download large size json

I am trying to download the large json data.
But it leads to Uncaught RangeError: Invalid string length.
Pls help to solve this problem,Thanks in advance.
Here is the Jsfiddle : http://jsfiddle.net/sLq3F/456/
You can use fetch(), Response.body.getReader() which returns a ReadableStream, TextDecoder(), Blob(), URL.createObjectURL().
Note, at device having limited RAM or low available disk space, after clicking Save at Save File dialog four minutes and twenty seconds 4:20 elapsed before the Save File dialog closed, followed by an additional one minute and thirty seconds 1:30 before the .crdownload extension was removed from the file at file manager GUI. During the first 4:20 period where the file is downloading to filesystem and the Save File dialog is visible the mouse pointer is movable, though the UI is temporarily unresponsive to clicks or attempts to change tabs. When the Save File dialog closes and the the file is still downloading to filesystem, having extension .crdownload the UI returns to normal functionality.
At the conclusion of the process described above the file was successfully downloaded to local filesystem having a total size of 189.8 MB (189,778,220 bytes).
<!DOCTYPE html>
<html>
<head>
<style>
code {
color:navy;
background-color:#eee;
padding:2px;
}
</style>
</head>
<body>
<button>Request File</button><br>
<progress min="0" max="189778220" value="0"></progress>
<output></output>
<br><br>
<label></label>
<script>
var url = "https://raw.githubusercontent.com/zemirco/sf-city-lots-json/master/citylots.json";
var button = document.querySelector("button");
var progress = document.querySelector("progress");
var label = document.querySelector("label");
var output = document.querySelector("output");
var request = (url) => {
label.innerHTML = `Requesting <code>${url}</code> at ${new Date()}.<br><br>`;
return fetch(url)
.then(response => response.body.getReader())
.then(reader => {
var decoder = new TextDecoder();
var json = "";
label.innerHTML += `Request successful.<br><br>Reading request body at ${new Date()}.<br><br>`;
return reader.read().then(function processData(result) {
if (result.done) {
// do stuff when `reader` is `closed`
return reader.closed.then(function() {
// return `json` string
return json;
});
};
json += decoder.decode(result.value);
output.innerHTML = ` ${json.length} of ${progress.max} bytes read`;
progress.value = json.length;
return reader.read().then(processData)
})
.then(function(data) {
var message = `Reading of <code>${url}</code> complete at ${new Date()}. <br><br>`
+ `${data.length} total bytes read. `
+ `Please allow up to 4 minutes for file to download `
+ `to filesystem after clicking <code>Save</code>.<br><br>`;
label.innerHTML += message;
var blob = new Blob([data], {
type: "application/json"
});
var file = URL.createObjectURL(blob);
var a = document.createElement("a");
a.download = "citylots.json";
a.href = file;
document.body.appendChild(a);
a.click();
var closeBlob = (e) => {
window.removeEventListener("focus", closeBlob);
blob.close();
URL.revokeObjectURL(file);
};
window.addEventListener("focus", closeBlob);
return message.replace(/<[^>]*>/g, "");
})
.catch(function(err) {
console.log("err", err)
})
});
}
var handleRequest = (e) => {
button.setAttribute("disabled", "disabled");
request(url).then(function(message) {
console.log(message);
button.removeAttribute("disabled");
})
};
button.addEventListener("click", handleRequest);
</script>
</body>
</html>
plnkr https://plnkr.co/edit/gewixzHZSKRXquZ2OVF2?p=preview
I guess you would need to loop through something in the JSON file and split it up into more manageable strings.
Tom
Do you have an example snippet the JSON file?
Do you have a server running on PHP?
if you do, I believe you must absolutely check your PHP.ini file or run a phpinfo page because php settings does limit the size of files transfer even if it isnt an external request. It could do that in other languages but I never had this problem except on PHP.
P.S. I did not see the size of the file
I think your json file is one of the "TOO BIG FOR JSON" scenarios. you know, if json file have so many records ( to be exact, based on a test, 100000 records make the browser hang and more then that failed to load in many browsers) its not recommend to use.
you can read this article for more information : HOW BIG IS TOO BIG FOR JSON?

NodeJS Streaming for Audio/Video with Client Side Control

i am building a simple streaming server to stream audio/video. below code gets the job done but when i click on time line on video nothing happens as i cannot fetch from that time. also need to send event regarding clikc to nodejs streaming and stream from where i clicked.
I had been able to come up with this. i send the file using the URL sendFile="some file" and then the node checks for that file. if successful i start getting the stream on my client side and i put it directly into video src. But i need morecontrol over this. such as when user click on certain timeline so that i can directly start strweaming from there.
app.get is used to get the location of the folder where i store the files.
used just express and nodejs
function FolderReaderMerger(path,pathToMerge,cb)
{
log("Reading File/Folder To Combine : ");
fs.readdir(path, function(err, audio)
{
fs.readdir(pathToMerge, function(err, audioText)
{
var obj ={};
global.list.audio =audio;
global.list.audioText =audioText;
obj.audio = audio;
obj.audioText = audioText;
cb(obj);
});
});
}
app.get("/audio",function(req,resp)
{
log("App Audio File Serv : ");
var playFile = req.param("playFile");
var filePath = {};
filePath.status =false;
if(playFile!=undefined)
{
log("Params File : "+playFile);
/* log("Requested URL : "+req.url);
log("Total Audio Files : "+global.list.audio.length);*/
var i =0;
while(i!=global.list.audio.length)
{
if(playFile==global.list.audio[i])
{
log("File Found : "+playFile);
//get files location
log(app.get("audioPath")+playFile);
filePath.status = true;
var filePath = app.get("audioPath")+playFile;
log("FILE PATH : "+filePath);
var stat = fs.statSync(filePath);
log(stat);
log(stat.size);
resp.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
var readStream = fs.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
log("Streaming.......");
readStream.pipe(resp);
}
else
{
log("Requested Resource Not Found");
}
i+=1;
}
//readStream = fs.createReadStream(app.get("audioPath"));
}
else
{
log("Requested Params Not Found");
resp.send(filePath);
}
});
http.listen(app.get("PORT"),function()
{
consolelog("--------------------------------------------------------");
console.log("Server Started On PORT: "+app.get("PORT"));
console.log("All NPM Initialized");
console.log("Please Wait Checking Connection Status...");
console.log("--------------------------------------------------------");
});
<video src="http://localhost:3000/audio?playFile='some media file"></video>
ANy help would be appreciated.This works on click side
But also need more control regarding click and events.

Categories

Resources