upload video to facebook from air android app - actionscript-3

i am attempting (for some time now) to upload a video to Facebook from an air for android app. i have recorded the video on the device, saved it to the device and have the path to the video stored in a string. i was advised to convert the video to byteArray and pass that into the FacebookMobile.uploadVideo method of the as3 Facebook api which i attempted to do but am getting a 353 You must select a video file to upload. error (from Facebook i presume).
file to byteArray
public function UICompleteHandler(event:MediaEvent):void
{
trace("Welcome back from the camera");
var media:MediaPromise = event.data;
trace("file info "+media.file.url + " - " + media.relativePath + " - " + media.mediaType);
filePath = media.file.url;
trace("Object encoding is: " + inBytes.objectEncoding + "\n\n" + "order file: \n\n");
readFileIntoByteArray(filePath, inBytes);
trace("length 1: "+inBytes.length);
trace("position 1: "+inBytes.position);
inBytes.position = 0; // reset position to beginning
inBytes.uncompress(CompressionAlgorithm.DEFLATE);
trace("position 2: "+inBytes.position);
inBytes.position = 0; //reset position to beginning
}
private function readFileIntoByteArray(fileName:String, data:ByteArray):void
{
var inFile:File = new File(fileName);
trace ("file to byte array "+ inFile.url);
trace ("file name var : "+fileName);
inStream.open(inFile , FileMode.READ);
inStream.readBytes(data);
inStream.close();
}
Upload to Facebook(attempt)
public function handleUpload(ev:TouchEvent)
{
trace ("posting to facebook - FileName: "+ accessCamera.fileName + " - FilePath: " + accessCamera.filePath);
var params:Object ={
title:'test upload on FB api',
description:'test upload on FB api',
fileName: accessCamera.fileName,
video: accessCamera.inBytes
}
//trace ("params.video = "+params.video);
FacebookMobile.uploadVideo('me/videos', onComplete, params);
}
private function onComplete( result:Object, fail:Object ):void
{
trace("facebook post onComplete called" );
if (result)
{
//result.id is id of post that was just posted
trace ("great");
}
else if (fail)
{
trace("post Failed");
trace('code: '+fail.error.code);
trace('message: '+fail.error.message);
trace('type: '+fail.error.type);
}
}
when i uncomment the trace params.video i get a huge amount of random characters which i thought to be the data of the byteArray
any guidance or help from anyone would be appreciated

Related

How to get byteArray or base64 string from RenderTexture Cocos2d-JS

I am making a game on cocos2d-JS for facebook in which there is a requirement of sharing a screenshot of the game.
I am able to take the screenshot but now I am unable to upload it in the Parse.com server because it requires base64 format or byte array. I am unable to find any solution of converting Sprite in to this format.. Here's my code so result when I do addchild its coming proper .. I have also added my commented code so that it will help to understand that I have tried lot of things but couldnt achieve the same.
shareToSocialNetworking: function () {
cc.director.setNextDeltaTimeZero(true);
var newsize = cc.director.getVisibleSize();
var renderText = new cc.RenderTexture(newsize.width,newsize.height);
renderText.begin();
cc.director.getRunningScene().visit();
renderText.end();
var result = cc.Sprite.create(renderText.getSprite().getTexture());
result.flippedY = true;
this._mainViewNode.addChild(result,6000);
//renderText.saveToFile("screenshot.jpg",cc.IMAGE_FORMAT_PNG);
//var based = renderText.getSprite().getTexture().getStringForFormat().toString();
//var data = based.getData();
var file = new Parse.File("screen.jpg", { base64: this.getBase64(result) });
//var file = new Parse.File("screen.jpg", data, "image/png");
var self = this;
file.save().then(function() {
// The file has been saved to Parse.
alert(file.url);
this.onSharePictureInfoLink(file.url());
}, function(error) {
// The file either could not be read, or could not be saved to Parse.
});
//
//var ccImage = renderText.newCCImage();
//
//var str = ccImage.getData();
},
is there any workaround that can be done
there is a private variable called _cacheCanvas, which is the instance of the offscreen canvas
you can simply do renderText._cacheCanvas.toDataURL()
Here's how you can take the screnshot from cocos2d-JS
screenshot: function (fileName) {
var tex = new cc.RenderTexture(winSize.width, winSize.height, cc.Texture2D.PIXEL_FORMAT_RGBA8888);
tex.setPosition(cc.p(winSize.width / 2, winSize.height / 2));
tex.begin();
cc.director.getRunningScene().visit();
tex.end();
var imgPath = jsb.fileUtils.getWritablePath();
if (imgPath.length == 0) {
return;
}
var result = tex.saveToFile(fileName, cc.IMAGE_FORMAT_JPEG);
if (result) {
imgPath += fileName;
cc.log("save image:" + imgPath);
return imgPath;
}
return "";
}
then make a Java call from Javascript
public static void ScreenShot()
{
Bitmap imageBitmap = BitmapFactory.decodeFile(Cocos2dxHelper.getCocos2dxWritablePath() + "/" + "screenshot.png");
String fileHolder = "SampleFolder";
File filepathData = new File("/sdcard/" + fileHolder);
//~~~Create Dir
try {
if (!filepathData.exists())
{
filepathData.mkdirs();
filepathData.createNewFile();
FileWriter fw = new FileWriter(filepathData + fileHolder);
BufferedWriter out = new BufferedWriter(fw);
String toSave = String.valueOf(0);
out.write(toSave);
out.close();
}
}
catch (IOException e1) {
}
//~~~Create Image
File file = new File("/sdcard/" + "Your filename");
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
imageBitmap.compress(CompressFormat.PNG, 100, ostream);
ostream.close();
}
catch (Exception e) {}
Uri phototUri = Uri.fromFile(file);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, phototUri);
//~~~Add Code Below
}
Do not forget to add permission for external storage

as3 converting video to byteArray

i am attempting to upload a video to facebook using the as3 api(FacebookMobile.uploadVideo) which accepts a video as either fieleReferance or byteArray. a followed the example # http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118666ade46-7d54.html for creating the byteArray i ma getting a 2058 error when uncompressing the byte array (this may be because i dident compress it but neither did adobe in the example).
if i comment this bit out i am getting an #353 You must select a video file to upload error from Facebook.
Byte Array Code:
public function UICompleteHandler(event:MediaEvent):void
{
trace("Welcome back from the camera");
var media:MediaPromise = event.data;
trace("file info "+media.file.url + " - " + media.relativePath + " - " + media.mediaType);
filePath = media.file.url;
trace("Object encoding is: " + inBytes.objectEncoding + "\n\n" + "order file: \n\n");
readFileIntoByteArray(filePath, inBytes);
trace("length 1: "+inBytes.length);
trace("position 1: "+inBytes.position);
inBytes.position = 0; // reset position to beginning
//inBytes.uncompress(CompressionAlgorithm.DEFLATE);
trace("position 2: "+inBytes.position);
inBytes.position = 0; //reset position to beginning
}
private function readFileIntoByteArray(fileName:String, data:ByteArray):void
{
var inFile:File = new File(fileName);
trace ("file to byte array "+ inFile.url);
trace ("file name var : "+fileName);
inStream.open(inFile , FileMode.READ);
inStream.readBytes(data);
inStream.close();
}
Handle Upload Code:
public function handleUpload(ev:TouchEvent)
{
trace ("posting to facebook - FileName: "+ accessCamera.fileName + " - FilePath: " + accessCamera.filePath);
var params:Object ={
title:'test upload on FB api',
description:'test upload on FB api',
fileName: accessCamera.fileName,
video: accessCamera.inBytes
}
trace ("params.video = "+params.video);
FacebookMobile.uploadVideo('me/videos', onComplete, params);
}
private function onComplete( result:Object, fail:Object ):void {
trace("facebook post onComplete called" );
if (result)
{
//result.id is id of post that was just posted
trace ("great");
}
else if (fail)
{
trace("post Failed");
trace('code: '+fail.error.code);
trace('message: '+fail.error.message);
trace('type: '+fail.error.type);
}
}
when i trace out the params.video i get a load of random characters. the problem seems to be facebook dosnt appear to see the bytearray(if i even success fully created it) as a video.

JSON request time out or inconsistent result

I am using JSON and YQL to access some data from an external domain.
http://jsfiddle.net/NdkPU/22/
But the problem I am having is that the code only works intermittently, sometimes I get a response, sometimes nothing is returned.
Obviously this is a very slow solution to access this data - so one reason I thought might be that it is timing out or there is a problem with the callback function.
Any ideas why the result is not working all the time?
// Start function when DOM has completely loaded
$(document).ready(function(){
requestCrossDomain("http://api.fool.com/caps/ws/Ticker/GOOG/Pitches/10?apikey=rW3550aXdsuJPg4bKEemC13x39jDNR6f", function (result) {
var num = 1;
var browserName = navigator.appName;
var doc;
if (browserName == 'Microsoft Internet Explorer') {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false'
doc.loadXML(result.results);
} else {
doc = (new DOMParser()).parseFromString(result.results, 'text/xml');
}
var xml = doc;
console.log("Data Loaded: " + xml);
// Build an HTML string
myHTMLOutput = '';
myHTMLOutput += '<table width="98%" border="1" cellpadding="0" cellspacing="0">';
myHTMLOutput += '<th>Text</th>';
// Run the function for each student tag in the XML file
$('Pitch',xml).each(function(i) {
PitchText = $(this).find("Text").text();
// Build row HTML data and store in string
mydata = BuildStudentHTML(PitchText);
myHTMLOutput = myHTMLOutput + mydata;
});
myHTMLOutput += '</table>';
myHTMLOutput += '<br>Rating: ';
myHTMLOutput += $('Ticker',xml).attr("Percentile");
// Update the DIV called Content Area with the HTML string
$("#ContentArea").append(myHTMLOutput);
});
});
function BuildStudentHTML(PitchText){
// Build HTML string and return
output = '';
output += '<tr>';
output += '<td>'+ PitchText + '</td>';
output += '</tr>';
return output;
}
// Accepts a url and a callback function to run.
function requestCrossDomain(site, callback) {
// If no url was passed, exit.
if (!site) {
alert('No site was passed.');
return false;
}
// Take the provided url, and add it to a YQL query. Make sure you encode it!
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=xml&callback=?';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON(yql, cbFunc);
function cbFunc(data) {
// If we have something to work with...
if (data.results[0]) {
if (typeof callback === 'function') {
callback(data);
}
}
// Else, Maybe we requested a site that doesn't exist, and nothing returned.
else throw new Error('Nothing returned from getJSON.');
}
}
It looks like it's just a slow API. I wrote a simple bash loop that timed that query using curl, and here were the timings:
7.4 sec
11.1 sec
11.2 sec
7.4 sec
11.1 sec
7.3 sec
10.2 sec
11.8 sec
11.3 sec
7.1 sec

Sending Json Form from Flash AS3

i am having one form accepting json post in Asp.net which i need to call from Flash As3...
i am using below code to do that. I have seen some post in which they say its working fine.
But i am encountering below Error
Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
Here is my code.
var messages:Array = new Array ();
messages.push({"From":fromemailTxt.text,"To": ToemailTxt.text,"Body": BodyText.text,"Subject":SubjectText.text});
var JsonObj:String = JSON.encode(messages);
trace(JsonObj);
var variables:URLVariables=new URLVariables(JsonObj);
RequestURL= srvStringURL;
var JSONLoader:URLLoader = new URLLoader();
JSONLoader.dataFormat=URLLoaderDataFormat.TEXT;
JSONLoader.addEventListener(IOErrorEvent.IO_ERROR, GetBookmarkURLError, false, 0, true);
JSONLoader.addEventListener(Event.COMPLETE, parseBookmarkURLResult, false, 0, true);
var hdr:URLRequestHeader = new URLRequestHeader("Content-type", "application/json");
var request:URLRequest = new URLRequest(RequestURL);
request.requestHeaders.push(hdr);
request.data=variables;
request.method = URLRequestMethod.POST;
try
{
JSONLoader.load(request);
}
catch (error:ArgumentError)
{
trace("An ArgumentError has occurred."+error.errorID.toString());
}
catch (error:SecurityError)
{
trace("A SecurityError has occurred.");
}
catch (error:Error)
{
trace("Unable to load requested document.");
}
Anybody have any idea on this??
Thanks
The error is, because you are passing incorrect string to URLVariables constructor. Do not use URLVariables. Instead pass data as string: request.data=JsonObj;
Below is the code I am using to consume REST Web service and pass json parameter to service it shows. Error #2032: Stream Error.
Andy idea what is going wrong
var ldr:URLLoader = new URLLoader();
ldr.dataFormat = URLLoaderDataFormat.TEXT;
var strData:String = "{\"gparam\": [ {\"productid\": \"" + productId + "\"},{\"message\": \"" + mesage + "\"},{\"googleappid\": \"" + googleappid + "\"},{\"senderid\": \"" + senderid + "\"},{\"appname\": \"" + appName + "\"},{\"userid\": \"" + userId + "\"},{\"receiverid\": \"" + receiverId + "\"} ]}";
var hdr:URLRequestHeader = new URLRequestHeader("Content-type", "application/json");
var req:URLRequest = new URLRequest("http://localhost/AndroidGCM/GCMNotification.svc/SendGCM");
req.requestHeaders.push(hdr);
req.method = URLRequestMethod.POST;
req.data = strData;
trace("data: " + req.data);
ldr.addEventListener(Event.COMPLETE,onComplete);
ldr.addEventListener(IOErrorEvent.IO_ERROR , onError);
ldr.addEventListener(SecurityErrorEvent.SECURITY_ERROR ,onSecurityErr);
ldr.load(req);
function onComplete(e:Event):void
{
trace("LOAD COMPLETE: " + ldr.data);
TextField(parMC.getChildByName("txtCheck")).appendText("\n LOAD COMPLETE: " + ldr.data);
}
function onSecurityErr(e:SecurityErrorEvent):void
{
trace("error: " + e.text );
}
function onError(e:IOErrorEvent):void
{
trace("error: " + e.toString());
}

Problems Displaying Profile Picture in Flash swf

I followed this tutorial Loading Facebook Profile Picture Into Flash SWF Using Graph API to get the users profile picture to show in my flash game, but I'm having some issues.
import com.facebook.graph.Facebook;
import com.facebook.graph.data.FacebookSession;
import com.facebook.graph.net.FacebookRequest;
import flash.events.Event;
import flash.events.IOErrorEvent;
//place your APP ID here
const APP_ID:String = "app_id";
//Initialize facebbok library
Facebook.init(APP_ID, HandleLogin);
function HandleLogin(response:Object, fail:Object):void
{
if(Facebook.getSession().accessToken)
{
LoadMyInfo();
LoadMyPicture();
}
}
function LoadMyInfo():void
{
Facebook.api("/me", MyInfoLoaded);
}
function MyInfoLoaded(response:Object, fail:Object):void
{
nameTextField.text = response.name;
}
function LoadMyPicture():void
{
debug.text = "Entered loadMyPicture() function ";
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, MyPictureLoaded, false, 0, true);
var request:URLRequest = new URLRequest("facebookProxy.php");
var variables:URLVariables = new URLVariables();
variables.path = Facebook.getImageUrl(String(Facebook.getSession().uid), 'large');
debug.appendText(" \nvariables.path: " + String(variables.path));
request.data = variables;
debug.appendText(" \nrequest.data: " + String(request.data))
loader.load(request);
debug.appendText(" \n" + String(loader.load(request)));
}
function MyPictureLoaded(event:Event):void
{
debug.appendText(" \nEntering MyPictureLoaded");
var loader:Loader = event.target.loader;
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, MyPictureLoaded);
loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, MyPictureLoadError);
var bitmap = Bitmap(loader.content);
bitmap.smoothing = true;
//Note: picturePlaceholder is just a blank movie clip on the Stage
bitmap.x = picturePlaceHolder.x;
bitmap.y = picturePlaceHolder.y;
bitmap.width = picturePlaceHolder.width;
bitmap.height = picturePlaceHolder.height;
picturePlaceHolder.addChild(bitmap);
debug.appendText(" \nBitmap is null: " + String(bitmap == null) +
" \nBitmap X: " + String(bitmap.x) + " Bitmap Y: " + String(bitmap.y) +
" \nBitmap width: " + String(bitmap.width) +
" \nBitmap height: " + String(bitmap.height))
}
function MyPictureLoadError(e:IOErrorEvent):void
{
debug.appendText("Loading Error");
}
This is what my code looks like after following the tutorials on the link above. With the debug I noticed that the function MyPictureLoaded is never called.
They never specified where I would call the function LoadMyPicture. I assumed it would go together with LoadMyInfo so I placed it there. They have a working example but no source code, so I'm hope someone here would shed some light on this.
EDIT 1
Here is what it looks like when I put it up on facebook. The last line debug.appendText(" \n" + String(loader.load(request))); is outputting undefined. I also made a change in the variables.path = Facebook.getImageUrl(String(Facebook.getSession().uid), 'large'); I added (String(), 'large') because in the docs it saying to pass strings into there. Edit: I realized adding String() is pointless.
var request:URLRequest = new URLRequest("facebookProxy.php");
Did you do the part of the tutorial that writes a server-side PHP proxy loader on your server?
If you don't have a file named facebookProxy.php on your server where you run this it won't work (the code is requesting "./facebookProxy.php" which probably doesn't exist). If you want to run this in the debugger on your local machine, you will need to make that file in the same directory as your swf and make sure you have apache/php running on your localhost.
If that's too much work for you, I would suggest following some of the examples from the API' project page: http://code.google.com/p/facebook-actionscript-api/downloads/detail?name=GraphAPI_Examples_1_6.zip&can=2&q=