Send an image file using sockets , Android to Python - python

Im trying to send an image from an android client to a python server , I have achieved it before with a python test client and the server. Basically my client app takes a form consisting of users details and an image. Once the user selects the image I get the uri in the onActivityResult method and parse it to a string Like so
selectedImagePath = selectedImageUri.toString();
when the user hits submit button on the form the sending activity is invoked with the form data as extras in an array in a bundle like so.
Bundle b=new Bundle();
b.putStringArray("regValues", new String[]{name,email,selectedImagePath});
in the sending activity I establish a connection with the server and attempt to send the image like so .
`
//establish link with the server
try{
//refer to the host computer's loopback interface
host = InetAddress.getByName("10.0.2.2");
link = new Socket(host,port);
in = new BufferedReader(new InputStreamReader(link.getInputStream()));
//access the strings that were passed to this activity
Bundle b = this.getIntent().getExtras();
String[] regFormValues = b.getStringArray("regValues");
//display connection confirmation
String message = in.readLine();
status.setText(message);
File myFile = new File (regFormValues[2]);
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = link.getOutputStream();
os.write(mybytearray,0,mybytearray.length);
os.flush();
link.close();
}
catch(IOException e ){
e.printStackTrace();
}
`
It connects to the server no problem , the
server creates a file for output to write the data to as usual but it just appears empty so no data is being recieved. I think it may be a problem with the file path on the client side. Any Ideas ?
EDIT: Basically I would like to know if I am accessing the image file in the right way or if you have any better suggestions for accessing and sending it.

Consider using methods such as File.exists() and File.isFile() to validate if the path is OK and whether the image is really there
Also check if the image even hits the wire - using tcpdump ro wireshark

I have solved it , as I use selectedImageUri = Uri.fromFile(photo); to get the uri if its taken by the camera and selectedImageUri = data.getData(); if its been selected by the file browser. I used selectedImagePath = selectedImagePath.substring(7); to strip the file:// form the camera's image path, resulting in a /sdcard/etc or wherever it stored it. To get the file path for the image chosen by the file browser i used this
// convert the image URI to the direct file system path of the image file
public String getRealPathFromURI(Uri contentUri) {
// can post image
String [] proj={MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery( contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
Now it works as expected.

Related

Linking Power BI with Python to download Reports and send it to a whatsApp contact

The problem statement I have in hand is, I am trying to automate the process of downloading reports from Power BI and send it to the various WhatsApp contacts with the help of Python.
Is this possible?
I found the Microsoft REST APIs which can be used to download the reports but I am getting lost in trying to configure my credentials and other things.
Check the reply in the following case Power BI API - How can I get reports from app.powerbi.com?
If you want to do this using an API, you will need Export Report In Group REST API. To use it, you need to acquire an access token and add it to your request header. You can acquire it by calling some of the AcuireToken methods from ADAL.
You can use code like this (please note there is no error checking in the example):
string clientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; // Obtain at https://dev.powerbi.com/apps
string redirectUri = "https://login.live.com/oauth20_desktop.srf";
string resourceUri = "https://analysis.windows.net/powerbi/api";
string authorityUri = "https://login.windows.net/common/oauth2/authorize";
AuthenticationContext authContext = new AuthenticationContext(authorityUri, new TokenCache()); // PM> Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory
var authenticationResult = await authContext.AcquireTokenAsync(resourceUri, clientId, new Uri(redirectUri), new PlatformParameters(PromptBehavior.Auto));
var accessToken = authenticationResult.AccessToken);
string powerBIApiUrl = "https://api.powerbi.com/v1.0/myorg/groups/{groupId}/reports/{reportKey}/Export"; // Replace groupId and reportKey with actual values
var request = WebRequest.Create(powerBIApiUrl) as HttpWebRequest;
request.KeepAlive = true;
request.Method = "GET";
request.ContentLength = 0;
request.ContentType = "application/json";
request.Headers.Add("Authorization", $"Bearer {accessToken}");
using (HttpWebResponse httpResponse = request.GetResponse() as System.Net.HttpWebResponse)
{
//Read httpResponse.GetResponseStream() to get the .pbix file
}
Also, there are other useful links:
https://community.powerbi.com/t5/Developer/Power-BI-REST-API-using-postman-generate-embed-token/m-p/310153#M9157
https://www.sqlshack.com/how-to-access-power-bi-rest-apis-programmatically/

SoftLayer API Nessus Scan Status / Report via python

I want to use python client to create a Nessus Security Scanner and check the status by getStatus and get the result by getReport method. While, I have read these helps by php(SoftLayer API Nessus Scan Status / Report via PHP). But how can i use these by python client?
When I call setInitParameter(scan_id) in by python, the exception as flows:
SoftLayerAPIError(Client): Function ("setInitParameter") is not a valid method for this service
i recomend you to read documentation of the client first:
https://github.com/softlayer/softlayer-python
https://softlayer-api-python-client.readthedocs.io/en/latest/
the init parameters are set like this:
clientService.getObject(id=myInitParameter)
here you can find more examples using the client:
https://softlayer.github.io/python/
Here you can find additional documentation:
http://sldn.softlayer.com/blog
And renember that with the Softlayer's python client unlike the php client the data are sending in json format so the request:
$client = SoftLayer_SoapClient::getClient('SoftLayer_Account', null, $apiUsername, $apiKey);
$accountInfo = $client->getObject();
$hardware = $client->getHardware();
foreach ($hardware as $server){
$scanclient = SoftLayer_SoapClient::getClient('SoftLayer_Network_Security_Scanner_Request', '', $apiUsername, $apiKey)
$scantemplate = new stdClass();
$scantemplate->accountId = $accountInfo->id;
$scantemplate->hardwareId = $server->id;
$scantemplate->ipAddress = $server->primaryIpAddress;
try{
// Successfully creates new scan
$scan = $scanclient->createObject($scantemplate);
} catch (Exception $e){
echo $e->getMessage() . "\n\r";
}
would be like this:
clientAccount = client['SoftLayer_Account']
accountInfo = clientAccount.getObject() #for this case we do not need init parameter
hardware = clientAccount.getHardware() #for this case we do not need init parameter
for server in hardware:
scanclient = client['SoftLayer_Network_Security_Scanner_Request']
scantemplate = {
"accountId": accountInfo["id"],
"hardwareId": server["id"],
"ipAddress": server["primaryIpAddress"]
}
scanclient.createObject(scantemplate)

Uploading file to Spring REST server using Python Requests

I am trying to upload a file using python requests to my java/scala spring rest server. I am getting the following response:
{"timestamp":1454331913056,"status":400,"error":"Bad Request","exception":"org.springframework.web.bind.MissingServletRequestParameterException","message":"Required MultipartFile parameter 'image' is not present","path":"/parking_api/images"}
my server code:
#RequestMapping(value = Array("/parking_api/images"), method = Array(RequestMethod.POST)) def images(#RequestParam("image") image: MultipartFile) = {
if (image.isEmpty){
// handle empty
new ResponseEntity(response, HttpStatus.BAD_REQUEST
} else {
// process
new ResponseEntity(response, HttpStatus.OK)
}
}
My client code:
requests.post(parking_webservice_address, files={"image": ("image", open(event.pathname, "rb"), "image/jpeg")})
I have tried:
setting files parameter in python code to just {"image":open(...)} instead of tuple
passing image data loaded to memory using open(...).read() to files parameter in python code
setting CommonsMultipartResolver in server like this
#Bean(name="multipartResolver")
public CommonsMultipartResolver multipartResolver(){
return new CommonsMultipartResolver();
}
setting multipart headers manually, but then it server expects boundary which is missing as things get from bad to worse
None of these options have worked for me. What am I missing?

Stream a song from SoundCloud using the Python API

I writing a little program that should stream a song from soundcloud..
my code is:
import soundcloud
cid="==="
cs="==="
un="==="
pw="==="
client = soundcloud.Client(
client_id=cid,
client_secret=cs,
username=un,
password=pw
)
print "Your username is " + client.get('/me').username
# fetch track to stream
track = client.get('/tracks/293')
# get the tracks streaming URL
stream_url = client.get(track.stream_url, allow_redirects=False)
# print the tracks stream URL
print stream_url.location
It just printing the usernsame, and the track URL
It prints something like this:
Your username is '==='
https://ec-media.soundcloud.com/cWHNerOLlkUq.128.mp3?f8f78g6njdj.....
Then, i want to play the MP3 from the URL. I can download it using urllib, but if it is a big file, it would take a lot of time.
What is the best way to stream the MP3?
Thanks!!
Before using the solution I suggest here, you should be aware of the fact that you must credit SoundCloud somewhere in your application and possibly in your audio player that users will be seeing that it is served through SoundCloud. Doing the opposite will be unfair and probably violate their terms of usage.
track.stream_url is not the end point URL associated with the mp3 file.
All the associated audio is only served 'on demand' when you send an http request with track.stream_url. Upon sending the http request you are being redirected to the actual mp3 stream (which is created just for you and will expire in next 15 mins).
So if you want to point the audio source you should at first get the redirect_url for the stream:
Below is the C# code which does what I am talking and it will give you the main idea - just convert it to Python code;
public void Run()
{
if (!string.IsNullOrEmpty(track.stream_url))
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(track.stream_url + ".json?client_id=YOUR_CLIENT_ID");
request.Method = "HEAD";
request.AllowReadStreamBuffering = true;
request.AllowAutoRedirect = true;
request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), request);
}
}
private void ReadWebRequestCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);
using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
{
this.AudioStreamEndPointUrl = myResponse.ResponseUri.AbsoluteUri;
this.SearchCompleted(this);
}
myResponse.Close();
}

Upload an image from iphone to GAE blobstore

I spent all this morning looking for a clear example on how to upload a picture taken with an iPhone to the blobstore, but without succeed.
Currently I have my iPhone app developed, which can send pics to the server in PHP, with this code in the server:
// Function to upload a photo in a file and save data in the DB
function upload($photoData, $descr, $phone) {
// Folder to upload data
$path = $_SERVER['DOCUMENT_ROOT']."/program/data/";
// Check if there was no error during the file upload
if ($photoData['error'] == 0) {
$result = query("INSERT INTO pics(descr, phone) VALUES('%s','%s')", $descr, $phone);
if (!$result['error']) {
// Inserted in the database, go on with file storage
// Obtain database link (in lib.php)
global $link;
// Get the last automatically generated ID
$idPhoto = mysqli_insert_id($link);
// Move the temporarily stored file to a convenient location
if (move_uploaded_file($photoData['tmp_name'], $path.$idPhoto.".jpg")) {
// File moved, all good, generate thumbnail
thumb($path.$idPhoto.".jpg", 180);
print json_encode(array('successful' => 1));
} else {
errorJson('Upload on server problem');
}
} else {
errorJson('Save database problem: '.$result['error']);
}
} else {
errorJson('Upload malfunction.');
}
}
The part in Objective-C that makes this works is (I'm using AFNetworking and the object API sharedInstance is an AFJSONRequestOperation class):
// Upload the image and the description to the web service
[[API sharedInstance] commandWithParams:[NSMutableDictionary dictionaryWithObjectsAndKeys:
#"upload", #"command",
UIImageJPEGRepresentation(originalPhoto, 70), #"file",
description, #"descr",
phoneNumber, #"phone",
nil]
onCompletion:^(NSDictionary *json) {
// Finished and response from server
if (![json objectForKey:#"error"]) {
// Success
[[[UIAlertView alloc]initWithTitle:#"Info"
message:#"Thanks"
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles: nil] show];
// Send a notification so the main view can reload the data
[[NSNotificationCenter defaultCenter] postNotificationName:#"updateStream" object:nil];
} else {
// Error
NSString* errorMsg = [json objectForKey:#"error"];
[UIAlertView error:errorMsg];
}
}];
This works fine and the images are saved on the server. But I want to make the same with datastore, which you can't save files. So I made a webpage to practice on save images, and I can upload images without any problem in the blobstore from an standard web form. This is the code I'm using to save it in GAE (forget about my own helper classes or functions like PicturePageHandler or render_page):
# Get and post for the create page
class Create(PicturePageHandler, blobstore_handlers.BlobstoreUploadHandler):
def get(self):
if self.user_logged_in():
# The session for upload a file must be new every reload page
uploadUrl = blobstore.create_upload_url('/addPic')
self.render_page("addPicture.htm", form_action=uploadUrl)
def post(self):
if self.user_logged_in():
# Create a dictionary with the values, we will need in case of error
templateValues = self.template_from_request()
# Test if all data form is valid
testErrors = check_fields(self)
if testErrors[0]:
# No errors, save the object
try:
# Get the file and upload it
uploadFiles = self.get_uploads('picture')
# Get the key returned from blobstore, for the first element
blobInfo = uploadFiles[0]
# Add the key and the permanent url to the template
templateValues['blobKey'] = blobInfo.key()
templateValues['servingUrl'] = images.get_serving_url(blobInfo.key(), size=None)
# Save all
pic = Picture.save(self.user.key, **templateValues)
if pic is None:
logging.error('Picture save error.')
self.redirect("/myPics")
except:
self.render_page("customMessage.htm", custom_msg=_("Problems while uploading the picture."))
else:
# Errors, render the page again, with the values, and showing the errors
templateValues = custom.prepare_errors(templateValues, testErrors[1])
# The session for upload a file must be new every reload page
templateValues['form_action'] = blobstore.create_upload_url('/addPic')
self.render_page("addPicture.htm", **templateValues)
My questions are:
Can I still using my Objective-C JSON call to upload a picture to the server or must I completely change the way to upload the picture?
How can I change the Python server code to get the picture from the JSON, if it is possible?
It's not exactly what you're after, but this might help:
http://brunofuster.wordpress.com/2011/03/11/uploading-an-image-from-iphone-to-appengine-blobstore-using-vraptor/

Categories

Resources