netstream no working on adobe air - amazon s3 - signed cloudfront - android

I can't seem to get net stream to work on my adobe air application. Android or desktop.
Here is the code with the valid link. The link works on VLC.
Any suggestions?
public function Main() {
url = "rtmp://s1p2w2yhnipjkt.cloudfront.net/cfx/st/mp4:demo.mp4?Expires=1594281188&Signature=AW0M39xRqX5bjhlw4EPMvdPzum8~gbK6Wsl7vkI3av6cWDXQ36lCfTlnpOXse6qiP9RSbuT-jhor84DHvZg7yPmvnnlPgAEQlndtgsBvzwUj~kGXES~~VWvHGVuUHTDnK~rAWcOmzpbRi-jWPpN71Ks2wnJeri596lqh2dOkUcg_&Key-Pair-Id=APKAI7XWAS4L22TVE3HA";
_netConnection = new NetConnection();
_netConnection.addEventListener(NetStatusEvent.NET_STATUS, onConnect);
_netConnection.client = {onBWDone:onNetConnectionBWDone};
_netConnection.connect(url);
_netConnection.connect("rtmp://s1p2w2yhnipjkt.cloudfront.net/cfx/st");
trace("connect")
}
private function onConnect(event:NetStatusEvent):void {
trace(event.info.code);
if(event.info.code == "NetConnection.Connect.Success")
{
_netStream = new NetStream(_netConnection);
_netStream.client = {onMetaData:onMetaData, onPlayStatus :onPlayStatus};
var video:Video = new Video();
video.attachNetStream(_netStream)
_netStream.play("mp4:demo.mp4");
addChild(video);
}
}

I tested your stream in my android device and it's working fine, and I think that your forgot to use the params with your stream, so you can do like this :
var url:String = 'rtmp://s1p2w2yhnipjkt.cloudfront.net/cfx/st',
// or rtmp://s1p2w2yhnipjkt.cloudfront.net:80/cfx/st
stream:String = 'mp4:demo.mp4?Expires=1594281188&Signature=AW0M39xRqX5bjhlw4EPMvdPzum8~gbK6Wsl7vkI3av6cWDXQ36lCfTlnpOXse6qiP9RSbuT-jhor84DHvZg7yPmvnnlPgAEQlndtgsBvzwUj~kGXES~~VWvHGVuUHTDnK~rAWcOmzpbRi-jWPpN71Ks2wnJeri596lqh2dOkUcg_&Key-Pair-Id=APKAI7XWAS4L22TVE3HA';
// ...
_netConnection.connect(url);
// ...
_netStream.play(stream);
Of course you have to add the INTERNET permission to your app to be able to get the stream, and also to be sure that your device can connect to the video server via the port 1935 or 80 (at worst).
Hope that can help.

Related

Xamarin.Android Mqtt Client with TLS Unauthorized result

I'm basically new to mobile development and stuck for a few weeks because,
I am unable to connect XAMARIN Android app with MQTTT over TLS.
Maybe i am using the wrong library or is it an Xamarin error?
My certificate is a .crt file from m21.cloudmqtt.com.
https://crt.sh/?id=5253106089
First was using System.Net MQTT but they are currently unable to work over TLS.
So i currently i am using MQTTNet, with (for the moment) the default certificate from m21.cloud.com which i have stored in Assets folder.I tested this local with and without a certificate and its working fine.
The MQTTNet Client with cert from local folder is like this, and works like it should:
var caCert = new X509Certificate2("C:/pathtocert.crt");
var source = new CancellationTokenSource().Token;
var token = source;
var factory = new MqttFactory();
var mqttClient = factory.CreateMqttClient();
var mqttOptions = new MqttClientOptionsBuilder()
.WithTcpServer(server, port)
.WithClientId(clientId)
.WithCredentials(username, pswd)
.WithTls(new MqttClientOptionsBuilderTlsParameters
{
UseTls = true,
Certificates = new List<X509Certificate> { caCert }
})
.Build();
mqttClient.ConnectAsync(mqttOptions, token).Wait(token);
To get the Certifcate from Android Assets Folder i used the same client code as above and t et the certificate i used:
using (var assetStream = await Xamarin.Essentials.FileSystem.OpenAppPackageFileAsync("filename.crt"))
using (var memStream = new MemoryStream())
{
assetStream.CopyTo(memStream);
caCert = new X509Certificate(memStream.ToArray());
}
I dont understand why its not working, for now its also okay if the certificate isn't used but it needs to use TLS. But tried, and i still get unauthorized error.
var mqttOptions = new MqttClientOptionsBuilder()
.WithTcpServer(server, port)
.WithClientId(clientId)
.WithCredentials(username, pswd)
.WithTls(new MqttClientOptionsBuilderTlsParameters
{
UseTls = true,
})
.Build();
Thanks in adnvance.

How do I send a serialized object over network stream to a tcp listener in Xamarin?

Can someone show me a code example of how to send serialized objects back and forth from a Xamarin Android application using a BinaryFormatter instead of Json? It's going to be over WiFi inside the Server Farm.
I'm currently trying to port a simple administrative console application over to an Xamarin Android forms application. I don't understand PCL yet or it's lack of [serializable] attribute. I've heard from the guys at Xamarin that I should probably try Android specific Xamarin instead of forms. I'm new to this so I'm not sure. This will be connecting to a custom Windows Service using standard TCPListeners. Any help would be greatly appreciated. Thanks.
This is an example of the type of console code that I am trying to port over.
public static void HeartBeatPulseListener()
{
Int32 hbPort = 8002;
Console.WriteLine("\nStarting Heart Beat Listener on Port: {0}", hbPort.ToString());
TcpListener heartBeatListener = new TcpListener(IPAddress.Any, hbPort);
heartBeatListener.Start();
while (true)
{
using (TcpClient client = heartBeatListener.AcceptTcpClient())
{
Console.BackgroundColor = ConsoleColor.DarkRed;
Console.ForegroundColor = ConsoleColor.Yellow;
NetworkStream netStream = client.GetStream();
IFormatter formater = new BinaryFormatter();
HeartBeatPulse pulseMSG = (HeartBeatPulse)formater.Deserialize(netStream);
if (pulseMSG != null) Console.WriteLine("\nPulse:{0} \n tStamp:{1}\n FROM:{2}\n Instance:{3} \n Original Unique:{4} \n Type: {5}", pulseMSG.Id.ToString(), pulseMSG.TimeStamp.ToString(), pulseMSG.A.ToString(), pulseMSG.ServerCoreInstanceId, pulseMSG.OriginalUnique, pulseMSG.Type);
if (pulseMSG.Roles.Count() > 1)
{
Console.WriteLine("\nRoles:");
foreach (string role in pulseMSG.Roles)
{
Console.WriteLine("\n{0}", role);
}
}
else Console.WriteLine("\nSum Ting Wong");
Console.ResetColor();
}
}
}

How to make RESTAPI calls in android using node.js

I have created a RESTAPI in Node.js and trying it to invoke into my android application. But i am not able to make the request to the Node.js Rest API.
My code are as follows:
Node.js
var restify = require('restify');
var request = require('request');
var http = require('http');
var appContext = require('./config.js');
function labsAPI(jsonparseStr) {
return JSON.stringify(labsapi);
}
function searchbase(req, res, next){
var options = {
host: appContext.host,
path: appContext.path+req.params.name+appContext.queryString
};
cbCallback = function(response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
jsonparseStr = JSON.parse(str);
json_res = labsAPI(jsonparseStr);
res.writeHead(200,{'Content-Type':'application/json'});
res.end(json_res);
});
}
http.request(options, cbCallback).end();
}
var server = restify.createServer({name:'crunchbase'});
server.get('/search/:name',searchbase);
server.listen(appContext.port, function() {
console.log('%s listening at %s', server.name, server.url);
});
After running my code like : localhost:8084/search/name
I am able to return the output to the browser a valid Json.
Now i want to consume this web service into my android application , I am not able to figure out how to do it.
I tried some of the example
http://hmkcode.com/android-parsing-json-data/
In the above blog in MainActivity.java i changed my url to
new HttpAsyncTask().execute("http://127.0.0.1:8084/search/name");
but it is displaying nothing
127.0.0.1 is the IP address for localhost. From your browser localhost resolves to your computer, from your Android device localhost resolves to your Android device, but your node application isn't running on it.
You need to figure out what's your computer's remote address. LAN or WLAN would be enough as long as your on the same network as your Android device.
Also make sure firewall settings allow access to your computer.

How to play a video from Amazon S3 in Android App?

I use aws-android-sdk-1.4.3/samples/S3_SimpleDB_SNS_SQS_Demo to preview my files stored on Amazon (Amazon Simple Storage Service). Looking through code I saw that they use this, to acces the files:
com.amazonaws.demo.s3.S3.getDataForObject (line 130)
public static String getDataForObject( String bucketName, String objectName ) {
return read( getInstance().getObject( bucketName, objectName ).getObjectContent() );
}
protected static String read( InputStream stream ) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream( 8196 );
byte[] buffer = new byte[1024];
int length = 0;
while ( ( length = stream.read( buffer ) ) > 0 ) {
baos.write( buffer, 0, length );
}
return baos.toString();
}
catch ( Exception exception ) {
return exception.getMessage();
}
}
}
Well, I have modified this methods to return ByteArrayOutputStream instead then I easily transform it to String or Bitmap (applying ByteArrayOutputStream.toByteArray() then using
BitmapFactory.decodeByteArray(byte[] data, int offset, int length, Options opts)).
So, it works on text-files and pictures. My problem is when I try to access videos. So, my questions are:
1.Using the method provided above, how could I get a video from ByteArrayOutputStream (ByteArrayOutputStream.toString()) and play it in a VideoView or using MediaPlayer or an approach... ?
2 . Does anybody know any other solution to this problem of preview videos stored on Amazon ? (I heard that on their sdk for IOS they use URLs to access files...)
PS: Supplying the file URL and open it in browser does not make sense, because this URLs expire after a wile.
First we have to provide the name of our bucket and the object (see aws-android-sdk-1.4.3/samples/S3_SimpleDB_SNS_SQS_Demo for a complet guide) we want to open then get the URL to our object:
AWSCredentials myCredentials = new BasicAWSCredentials("YOUR_AMAZON_ACCESS_KEY_ID", "YOUR_AMAZON_SECRET_KEY_ID");
AmazonS3 s3client = new AmazonS3Client(myCredentials);
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName);
URL objectURL = s3client.generatePresignedUrl(request);
Now, just play the video in a video view, supplying the URL obtained:
getWindow().setFormat(PixelFormat.TRANSLUCENT);
mediaCtrl = new MediaController(this);
mediaCtrl.setMediaPlayer(videoView);
videoView.setMediaController(mediaCtrl);
Uri clip = Uri.parse(objectURL.toString());
videoView.setVideoURI(clip);
videoView.requestFocus();
videoView.start();
I want to give thanks to #CommonsWare for
indicating me through REST API (even the code I used is from aws-sdk reading the REST API documentation helped me and show also other ways of requesting Amazon objects)
indicating me to use generatePresignedUrl()
the code for playing the video is also inspired from his materials.
1.Using the method provided above, how could I get a video from ByteArrayOutputStream (ByteArrayOutputStream.toString()) and play it in a VideoView or using MediaPlayer or an approach... ?
Maybe you could get it to work by publishing the byte array through a ContentProvider and openFile(). Here is a sample project where I demonstrate serving a file by means of a custom InputStream this way.
The media subsystem is rather fussy, though, and so I do not give you good odds on this working.
2 . Does anybody know any other solution to this problem of preview videos stored on Amazon ? (I heard that on their sdk for IOS they use URLs to access files...)
Last I checked, S3 had a REST API that you could use to generate URLs to the videos. I'd hand that URL to MediaPlayer or VideoView.
Supplying the file URL and open it in browser does not make sense, because this URLs expire after a wile.
But you control how long "a wile [sic]" is. Make it be 24 hours or something.
#AlexAndro answer
AWSCredentials myCredentials = new BasicAWSCredentials("YOUR_AMAZON_ACCESS_KEY_ID", "YOUR_AMAZON_SECRET_KEY_ID");
AmazonS3 s3client = new AmazonS3Client(myCredentials);
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName);
URL objectURL = s3client.generatePresignedUrl(request);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
mediaCtrl = new MediaController(this);
mediaCtrl.setMediaPlayer(videoView);
videoView.setMediaController(mediaCtrl);
Uri clip = Uri.parse(objectURL.toString());
videoView.setVideoURI(clip);
videoView.requestFocus();
videoView.start();
solved my problem, but it needs to define your region
using
s3client.setRegion(Region.EU_Paris.toAWSRegion())
EU_Paris is for eu-west-3
here you can find all regions

Flex/Flash builder - app works in simulator or iOS but not android - HTTPService

Ok, I have an app I've been writing in Flash builder that makes several HTTPService requests to a server to gather some data about the user. In one view it goes and downloads a string from a server, it then splits the string using delimiter ":" and then adds the components to an array to populate a Spinnerlist. In the simulator this works great, if I package the app for iOS and install it on my iPhone - it works great. But when I try to run it to my Android device, it doesn't work. It acts as though it is working, it loads the view with the SpinnerList on it but the list is empty. I can't seem to figure it out.
Some things I've tried: the XML settings i have enabled the internet access to the android device, in fact, earlier in the app when the user logs in the phone make a very similar server call which works fine on all devices.
This issue has me completely dumbfounded, and help would be greatly appreciated!!
here is the code that makes the request and separates the data.
HttpService Request:
<mx:HTTPService id="CommonHTTP" url="http://dispatch.americantaxi.com:8080/AT/servlet/OnlineOrderServices?command=retrieveCustomerCommonPlaces&customerId={data.ID}" resultFormat="text"/>
Sorting code:
protected function button5_clickHandler(event:MouseEvent):void
{
PickUpType = "Common";
data.PickUpType = PickUpType;
var CommonDataString:String = new String(CommonHTTP.lastResult);
trace("String " + CommonDataString)
var Arr1:Array = [];
Arr1 = CommonDataString.split("|");
trace("arr1 length " + Arr1.length);
var ArrCount:Number = new Number(Arr1.length);
var Arr2:Array = [];
for (var i:Number = 0; i < (ArrCount - 1); i++) {
var currentSelect:String = new String(Arr1[i]);
Arr2 = currentSelect.split(":");
var currentName:String = new String(Arr2[1]);
trace("Add: " + currentName);
CommonPlacesArray.addItem(currentName);
}
data.CommonPlacesArray = CommonPlacesArray;
navigator.pushView(CommonPlaces, data);
}

Categories

Resources