Create POST Request in air /as3 for youtube direct upload - actionscript-3

I'm developing a simple youtube app in adobe air, so far I could get the approval window in youtube and getting the token for uploading. However I'm stuck in the part where you send the data on POST with all the information (https://developers.google.com/youtube/2.0/developers_guide_protocol_direct_uploading)
I already loaded my video data as a bytearray, what I need is to create the whole POST request containing all the information as it shows in the link. (the xml atom feed, the bytearray data, etc.) I have all the information needed, I just need to structure the POST request.
How to do that in as3/air? Do I create all the information as URLVariables? which ones are headers and which ones arent? How do you add the --< boundary_string> to the POST? How do you add the bytearra to the POST? All help is highly appreciated.
Thanks!

I have always done something like this when sending POST variables:
<fx:Declarations>
<s:HTTPService id="loginServ" resultFormat="text" result="onResult(event)" method="POST" url="http://www.myurl.com/login.php"/>
</fx:Declarations>
Then you would have two functions, one for sending the request and one for handling the result you get back:
private function login():void{
//Make a new Object to hold all of your POST variables
var reqInfo:Object = new Object();
//Then set the properties of that Object to be each POST variable
reqInfo.username = "admin";
reqInfo.password = "password";
//Finally, send the request with the Object as the parameter
loginServ.send(reqInfo);
}
private function onResult(e:ResultEvent):void {
trace("Result:" + e.result);
}

Related

Facebook Graph API get page post's attachments

I am trying to get the url of an image attachment published by a facebook page. The goal is to embed that image in a webpage in order for the website to always display the last image attachment published by the page. I own both website and FB page.
I have yet not grasped all the details on handling Facebook Graph API, but here is what I did so far:
1) in FB developers website, I have created an application, getting its App ID and secret;
2) I used that information to get an access token (just pasted in my browser the following code:
https://graph.facebook.com/oauth/access_token?client_id={my-client-id}&client_secret={my-client-secret}&grant_type=client_credentials
3) in my website, I have loaded Facebook JS SDK after the body tag; and got also my Facebook page ID from Facebook Page administration;
4) now the real question begins: how can I query Facebook to get the information that I need – the source url of the last published image?
The best result I have gotten so far was by making a getJSON call with the help of jQuery:
var fbfeed = $j.getJSON('https://graph.facebook.com/{my-page-id}/feed?access_token={my-token}&fields=attachments&limit=1');
This will get and store a JSON array in the fbfeed variable (please correct me if I'm wrong). One of the keys of that array is called "src" which contains the source url of the attachment – the information I need to embed that picture in my website;
I have the following problems / concerns:
- I have not found the way to retrieve the value of the "url" key – how can I do that? How can I parse the fbfeed variable and extract the value of the "url" key?
– I have concerns with my usage of the access token:
is it problematic to expose the access token in this way, by using it in a jQuery function? Is it a security risk? If so, can I "mimic" this request but using a server side language such as PHP?
Will this access token expire (i.e. will I need to repeat step 2 from time to time?). So, imagining that I can get this to work, will I need from time to time to "refresh" the access token?
Thanks for your help.
I have managed to get the information I needed using server-side code, although it may not be the most "clean solution": it will iterate through the last 5 posts of my page until it finds an image and a post url:
<?php
$url = 'https://graph.facebook.com/{page-id}/feed?access_token={access-token}&fields=attachments,link&limit=5';
$json = file_get_contents($url);
$json_data = json_decode($json, true);
for($count = 0; $count < 5; $count++) {
$imagesource = $json_data['data'][$count]['attachments']['data'][0]['media']['image']['src']; // gets the image url
$postlink = $json_data['data'][$count]['link']; // gets the post url
if (isset($imagesource) && isset($postlink)) {
// do stuff with the image and post url
break;
};
};
// then I can do other stuff as fallback if the image url and post url are not found

How to display push notifications using SignalR in MVC

I am using SignalR in MVC to display information in a basic chat type device in MVC. This is all working ok but I want to display information from a Json payload that has been deserialized like this:
Dim iss As IssueObjectClass = JsonConvert.DeserializeObject(Of object)(json)
The information does not have to being displayed does not just have to be an object it could be a variable as well, for example I could also display this:
Dim key = iss.issue.key
I have the code for the connection using the chat hub device which is displaying basic information (Message and username). Is this the way that I should try and display my Json using SignalR. I know that SignalR is used for real-time web applications but I am unsure on how it could display information that has been fired from a webhook as a Json payload.
This is how I am displaying the messages in the chat hub, but I want to display information that is coming from a webhook unrelated to anything that has been typed on the application. I want to display information from a HTTP POST from JIRA:
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
$('#discussion').append('<li><strong>' + encodedName + '</strong>: ' + encodedMsg + '</li>');
$('#discussion').text = encodedMsg;
How can I integrate SignalR with Json to display it?
It's a pretty simple thing to do, and a common case with SignalR. In your code where to receive and deserialize your object, you just have to call something like:
var context = GlobalHost.ConnectionManager.GetHubContext<YourHub>();
context.Clients.All.broadcastIssue(iss);
On your client you'll have to define a handler this way before you start the connection:
var yourHubProxy = $.connection.yourHub;
yourHubProxy.client.broadcastIssue = function (iss) {
// ...do your stuff...
};
This is very basic code which would need to be better organized, but it should put you on the right track. My advice is you go through the official SignalR documentation, which is extensive and well done, in particular the guides to the APIs.

How to log in programmatically to a web page

I need some help to post username and password to a web page and then invoke the click event for the log in.
In order to better understand what I'm trying to do, a good example could be the following one:
programmatically send to a bank account's web page username and password (in the relevant inputs) and then, once logged in, retrieve the balance.
This means that in my app I'll have a XAML page with 2 textboxes, 1 button and 1 textblock.
Parse a site is quite easy, so that I'd be able to get the balance but I can't send the data to the server for the log in.
I've already read several examples with WP8 but none of them allows me to understand how to proceed with WP8.1 where, apparently, things are little bit different.
I've tried with this code where I assumed the inputs are called "user" and "password":
private async void LogIn_Click(object sender, RoutedEventArgs e)
{
string url = "http://www.something.com";
WebRequest request = WebRequest.Create(url);
string postData = "user=" + textBoxUser.Text + "&password=" + textBoxPassword.Text;
byte[] send = Encoding.UTF8.GetBytes(postData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
Stream sout = await request.GetRequestStreamAsync();
sout.Write(send, 0, send.Length);
sout.Dispose();
var myHttpClient = new System.Net.Http.HttpClient();
var response = await myHttpClient.GetAsync(url);
var dataBack = await response.Content.ReadAsStringAsync();
//Debug:
Debug.WriteLine(dataBack);
}
Even though I don't receive any error, the inputs in the response are empty and moreover I don't know how to invoke the click event of the button in the web page to submit the data.
In addition, I don't want to open the web page since everything would be managed by the 4 controls of the app.
Is there anybody who can give some suggestion or address me where I can find something which suits my need?
Thanks
Looks like you're already on the right path: putting together the correct POST request the way a browser would send it after the user submits the form.
You may however need to set Referer parameters and maybe a CSRF token or such in addition to naming the parameters correctly. The best approach would be to submit the form in an actual browser and look at the request that it sends via the built-in developer tools, then reverse-engineer that one from within your app.

calling a webservice without using a wsdl file

I need to make a call to a webservice and at the moment i am doing it this way:
private var myWebService:WebService = new WebService();
myWebService.loadWSDL('path to wsdl file');
myWebService.addEventListener(ResultEvent.RESULT , function(event:ResultEvent):void {
trace(event);
});
myWebService.addEventListener(FaultEvent.FAULT , function(event:FaultEvent):void {
trace(event);
});
myWebService.soapcallName();
Now i would like to do the same thing but without loading the WSDL file and doing the soapcalls directly to the right url. Is this possible?
Yes, I had to do this when our WS calls had to hit a proxy in a DMZ, but the WSDL for the ACTUAL service was behind a firewall and unreachable. But it is a tricky process.
First you will need to create the soap post requests manually. You can read all about the structure on wikipedia http://en.wikipedia.org/wiki/SOAP . This means you will need to generate all calls manually since you can't say SomeService.SomeMethod without the wsdl loaded. Now the next problem you will face is actually sending it out. Because you need to add custom http headers on a POST, you will need to build the full request document (strings and line breaks etc) and send it over a socket (HTTPService will not support custom headers on a POST). If you need more help getting this going, I can add further examples on here.
Example:
You need to basically create a method to generate SOAP Envelopes. Here's a quick i.e. from the link I gave you...
private function getStockPrice(symbol:String):String{
// you can do this with xml also and call toString() on it later
var envelope:String = "<?xml version=\"1.0\"?>";
envelope += "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\">";
envelope += "<soap:Header></soap:Header>";
envelope += "<soap:Body><m:GetStockPrice xmlns:m=\"http://www.example.org/stock\">";
envelope += "<m:StockName>" + symbol + "</m:StockName>";
envelope += "</m:GetStockPrice></soap:Body></soap:Envelope>";
return envelope;
}
Then you call getStockPrice("IBM") which will return the ready to go SOAP envelope that you will use as the POST body of your call. Note that in the example, you will have to know the information that would have been in the WSDL ahead of time like method names, param names etc. Use the Socket() class to send the post body to the server since you will need to add a custom SOAPAction header. If you need help with that part, here is a class to begin hacking on that already does that... use it instead of HTTPService. RestHTTPService.

Salesforce REST API and the DELETE method

I'm using Adobe AIR and integrating with the force.com platform via the REST API, and so far it's been relatively smooth sailing, but I'm coming unstuck on using the DELETE method.
The documentation is simple enough:
Deleting an Account Record
Use the DELETE method to delete a record.
In this example, an Account record is deleted.
Example usage for deleting fields in an Account object
curl https://instancename.salesforce.com/services/data/v20.0/sobjects/Account/001D000000INjVe
-H "Authorization: Bearer token" -H "X-PrettyPrint:1" -X DELETE
Example request body for deleting an Account record
none required
Example response body for deleting an Account record
none returned
My code is below, note that the second parameter of HTTPConnection.send() is the method to call.
var headers:Object = new Object();
headers["Authorization"] = "Bearer "+ConnectionAccessToken;
var url:String = ConnectionInstanceURL + "/services/data/v"+_apiVersionNumber+"/sobjects/"+type+"/"+id;
var response:RESTResponse = new RESTResponse(callback);
var httpCallback:IResponder = new mx.rpc.Responder(response.resultHandler,response.faultHandler);
HTTPConnection.send(headers,"DELETE",url,httpCallback);
Similar code works perfectly for other operations, and the weird thing is that this doesn't fail per se, rather it receives a success response, but gets the record in question back with all of it's fields. It would appear that I'm seeing the results of [select * from Object where Id = <id>, and just to clarify the record is not deleted. The object doesn't have any master detail relationships, so I'm not sure what else might be stopping this delete from happening — has anyone run into this before or have suggestions on how to resolve it?
With the setup I am using (where HTTPConnection is a custom class using HTTPService internally), the Adobe documentation states that the only HTTP methods available for me to use are just GET and POST:
"Optionally, you can pass parameters to the specified URL. When you do not go through the server-based proxy service, you can use only HTTP GET or POST methods. However, when you set the useProxy property to true and you use the server-based proxy service, you can also use the HTTP HEAD, OPTIONS, TRACE, and DELETE methods."
This is why the delete was failing as it must have been sending as a GET instead as per jkraybill's comment above. After experimenting I have found that POST can be used, with the actual method to call included as a parameter to the URL:
HTTPConnection.send(headers,"POST",url + "?_HttpMethod=DELETE",httpCallback);