Upload a video on Youtube by means of XHR2 - youtube-api

My customer wants to show progress dialog just as user is uploading video on Youtube.
I write something like:
element = document.forms.uploadNewVideoForm.file;
var fd = new FormData();
console.log(element.files);
fd.append('token', $scope.uploadData.token);
fd.append('file', element.files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", $scope.uploadProgress, false);
xhr.addEventListener("load", $scope.uploadComplete, false);
xhr.addEventListener("error", $scope.uploadComplete, false);
xhr.addEventListener("abort", $scope.uploadComplete, false);
xhr.open("POST", $scope.uploadData.uploadUrl + '?nexturl=' + encodeURIComponent('http://local.app.com:8000/OK'));
xhr.onreadystatechange = function ( response ) {};
xhr.send(fd);
This code start perfectly, but it fails when Youtube redirects to callback URL.
POST http://uploads.gdata.youtube.com/action/FormDataUpload/<token here>?nexturl=http%3A%2F%2Flocal.app.com%3A8000%2FOK
302 Moved Temporarily
Location: http://local.app.com:8000/OK
Here request interrupts and the error callback is invoked.

Take a look at the following sample (source code). It breaks the upload into two parts:
A CORS request to upload the metadata.
A form POST to upload the actual video.
Unfortunately the upload page doesn't support CORS yet, so this is the best you can do.

Related

How to integrate OAuth2.0 login in electron

I am newbie to electron and I am currently trying to implement an OAuth2.0 API which requires a callback URI. Url callback requires valid URL (https://myserver.com/sucess). so i tried this code snippet but does not work.
// Your GitHub Applications Credentials
var options = {
client_id: 'your_client_id',
client_secret: 'your_client_secret',
scopes: ["user:email", "notifications"] // Scopes limit access for OAuth tokens.
};
app.on('ready', () => {
// Build the OAuth consent page URL
var authWindow = new BrowserWindow({ width: 800, height: 600, show: false, 'node-integration': false });
var githubUrl = 'https://github.com/login/oauth/authorize?';
var authUrl = githubUrl + 'client_id=' + options.client_id + '&scope=' + options.scopes;
authWindow.loadURL(authUrl);
authWindow.show();
function handleCallback (url) {
console.log(url);
}
// Handle the response from GitHub - See Update from 4/12/2015
authWindow.webContents.on('will-navigate', function (event, url) {
handleCallback(url);
});
authWindow.webContents.on('did-get-redirect-request', function (event, oldUrl, newUrl) {
handleCallback(newUrl);
});
// Reset the authWindow on close
authWindow.on('close', function() {
authWindow = null;
}, false);
});
also, i used angular js route but does not work either.
so I'm wondering if there is a way to run server inside electron app to serve app from URL (https://localhost:3000) and if so how this will affect app behavior at packaging and distributing time, i means does the app will run from the same port
... any suggestions will help about how i can approach this problem. thank you
I had the same issue last week, i needed to integrate my electron app with vkontakte api which uses form of OAuth protocol. What you can do:
1) You launch local node http server, probably in separate process as i did.
2) You request code through oauth link and set redirect uri as http://127.0.0.1:8000/, for some reason https://localhost didn't work for me.
3) In main process you wait for message with code from server, on server implemented corresponding logic (when you receive request and code in it send through process.send back to parent message with code)
4)You request access token from main process, you shouldn't change redirect_uri. You again catch response from your server.
5) You get access_token, you kill server...
But when i did all this i read their docs till end and there was stated that standalone apps, like mine for desktop could receive token in easier way through "implicit flow", and you can get your token with only one call. Hope my experience could be extrapolated on your issue. Good luck!

XMLHttpRequest.withCredentials in ruby in rails

I want to make HTTP requests from the browser to the server configured with XHR's withCredentials: true.
I found this documentation of java script.
Is there any similar thing in ruby on rails?
Is this config.http_authenticatable_on_xhr = true anyhow related to my requirement?
Thanks.
I fixed this by adding the below lines in a JS file and placing the file in the path app/assets/javascripts/ and including it in the app/assets/javascripts/application.js as //= require dummy_request
dummy_request.js contains:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/', true);
xhr.withCredentials = true;
xhr.send(null);
Using the above technique you can send the request for the first time page being opened. If you want to make request for every particular interval, you can use something like below:
setInterval(function(){ var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/', true);
xhr.withCredentials = true;
xhr.send(null); }, 3000);
Using the above code, you can send the request at an interval of every 3sec.
Thanks.

Send RadFlowDocument as PDF to user

I'm using VS 2013, VB.Net, and Telerik 2016 Q1 in an MVC application. I'm using the Telerik RadFlowDocument to create a report, and send it to the user as a pdf. I have successfully created the report and saved it locally. My issue is when I try to convert it to a memory stream and send it back to the user, the user is never given the option to download the report.
I have a button that starts the process via ajax:
function supervisorPDF() {
$.ajax({
url: '#Url.Action("GenerateSupervisorReportPDF", "InteriorReport")',
type: 'POST'
})
.success(function (result) {
})
.error(function (xhr, status) {
alert(status);
})
}
I have a sub routine that receives the ajax call and then generates the report:
Sub GenerateSupervisorReportPDF()
Dim generator As New PdfGenerator
Dim selectedSupervisorName = System.Web.HttpContext.Current.Session("selectedSupervisorName").ToString()
Dim selectedSupervisorIdNumber = System.Web.HttpContext.Current.Session("selectedSupervisorIdNumber").ToString()
Dim report As New RadFlowDocument
Dim viewModel As New SupervisorReportViewModel
Dim model = viewModel.getSupervisorReportInfo(selectedSupervisorName, selectedSupervisorIdNumber)
report = generator.generateSupervisorPdf(model)
Dim provider As New PdfFormatProvider()
Dim output As New MemoryStream
provider.Export(report, output)
Dim buffer As Byte()
Try
buffer = output.ToArray
Response.ClearContent()
Response.ClearHeaders()
Response.ContentType = "application/pdf"
Response.OutputStream.Write(buffer, 0, buffer.Length)
Response.AddHeader("Content-Disposition", "attachment;filename=SupervisorReport.pdf")
Response.End()
Catch ex As Exception
End Try
End Sub
In this subroutine, if I declare output as a local file path everything works as intended. However when using this implementation my Response.OutputStream always ends up null. No errors are thrown.
What do I need to change to send this report back to the user in such a way that they have the option of downloading the report?
You won't be able to do this via ajax.
In order for the browser to receive and handle
Content-Disposition:attachment
it must be browsed to directly.
The ajax call may download the binary to jquery, but jquery won't be able to save it locally.
Easiest option is to have the browser open a link to the action that generates the PDF directly, eg:
<a href='#Url.Action("GenerateSupervisorReportPDF", "InteriorReport")'>download report</a>
As an extra, you can reduce all of the Response. code to a simple return FileStreamResult(... and it should handle prompting the user to save etc - I'll leave this to you (as I don't have the exact syntax to hand)

XMLHttpRequest() does not work in the latest versions of Firefox?

In my addons I always used new XMLHttpRequest () and it worked perfectly.
Now all requests ajax stopped working.
Currently new XMLHttpRequest () is causing the following error: ReferenceError: XMLHttpRequest is not defined
So I changed my code to:
try {
var XMLHttpRequest;
if (typeof(XMLHttpRequest) == "undefined")
XMLHttpRequest = content.XMLHttpRequest;
}
catch (e) {
alert(e);
}
var xmlhttp = new XMLHttpRequest();
...
Sometimes the request usually works, but sometimes not.
The code "alert(e);" is never executed, then there is no error there.
I can not understand why sometimes it works and sometimes not.
Previously I used only var xmlhttp = new XMLHttpRequest(); and always worked.
Now how do I create a new ajax request?
As I said in a comment, when you are running in the context of a browser window (like code loaded by an overlay to that window) then XMLHttpRequest should definitely be available. I verified that just in case and it works for me.
But in case everything else fails you can still instantiate the XPCOM component corresponding to XMLHttpRequest directly:
var xmlhttp = Components.classes["#mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Components.interfaces.nsIXMLHttpRequest);
xmlhttp.open(...);

HTML5 App Cache not working with POST requests

I'm working on a web application and I went through the necessary steps to enable HTML5 App Cache for my initial login page. My goal is to cache all the images, css and js to improve the performance while online browsing, i'm not planning on offline browsing.
My initial page consist of a login form with only one input tag for entering the username and a submit button to process the information as a POST request. The submitted information is validated on the server and if there's a problem, the initial page is shown again (which is the scenario I'm currently testing)
I'm using the browser's developers tools for debugging and everything works fine for the initial request (GET request by typing the URL in the browser); the resources listed on the manifest file are properly cached, but when the same page is shown again as a result of a POST request I notice that all the elements (images, css, js) that were previously cached are being fetched form the server again.
Does this mean that HTML5 App Cache only works for GET requests?
Per http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#the-application-cache-selection-algorithm it appears to me that only GET is allowed.
In modern browsers (which support offline HTML), GET requests can probably be made long enough to supply the necessary data to get back data you need, and POST requests are not supposed to be used for requests which are idempotent (non-changing). So, the application should probably be architected to allow GET requests if it is the kind of data which is useful offline and to inform the user that they will need to login in order to get the content sent to them for full offline use (and you could use offline events to inform them that they haven't yet gone through the necessary process).
I'm having exactly the same problem and I wrote a wrapper for POST ajax calls. The idea is when you try to POST it will first make a GET request to a simple ping.php and only if that is successful will it then request the POST.
Here is how it looks in a Backbone view:
var BaseView = Backbone.View.extend({
ajax: function(options){
var that = this,
originalPost = null;
// defaults
options.type = options.type || 'POST';
options.dataType = options.dataType || 'json';
if(!options.forcePost && options.type.toUpperCase()==='POST'){
originalPost = {
url: options.url,
data: options.data
};
options.type = 'GET';
options.url = 'ping.php';
options.data = null;
}
// wrap success
var success = options.success;
options.success = function(resp){
if(resp && resp._noNetwork){
if(options.offline){
options.offline();
}else{
alert('No network connection');
}
return;
}
if(originalPost){
options.url = originalPost.url;
options.data = originalPost.data;
options.type = 'POST';
options.success = success;
options.forcePost = true;
that.ajax(options);
}else{
if(success){
success(resp);
}
}
};
$.ajax(options);
}
});
var MyView = BaseView.extend({
myMethod: function(){
this.ajax({
url: 'register.php',
type: 'POST',
data: {
'username': 'sample',
'email': 'sample#sample.com'
},
success: function(){
alert('You registered :)')
},
offline: function(){
alert('Sorry, you can not register while offline :(');
}
});
}
});
Have something like this in your manifest:
NETWORK:
*
FALLBACK:
ping.php no-network.json
register.php no-network.json
The file ping.php is as simple as:
<?php die('{}') ?>
And no-network.json looks like this:
{"_noNetwork":true}
And there you go, before any POST it will first try a GET ping.php and call offline() if you are offline.
Hope this helps ;)

Resources