IPFS read data from network - android

I am working on one application, where I am using IPFS for storing and getting files.
I am using the following API for Android,
https://github.com/ligi/ipfs-api-kotlin
As per the doc, I can get data from IPFS using following code,
ipfs.get.cat("hash code of IPFS file")
but here it returns everything in string format, even if the uploaded file is Image.
How Can I know the content type of the file and download the same format?

IPFS doesn't allow to store metadata such as the content type alongside the content itself.
Something you could do in Java that worked for me:
private static String guessContentType(InputStream content) {
try {
String guessedContentType = URLConnection.guessContentTypeFromStream(content);
if (!StringUtils.isEmpty(guessedContentType)) {
return guessedContentType;
} else {
return MediaType.APPLICATION_OCTET_STREAM_VALUE;
}
} catch (IOException e) {
throw new RuntimeException("Unable to guess content type", e);
}
}

Related

Parsing received MMS for Images and Text

I am developing an SMS-MMS vault application for android. Its purpose will be to correct a couple of vulnerabilities existing in Android, as well as creating a "safe" communication space between certain contacts (Encrypted SMS and MMS).
I have implemented all the intended functionalities, except the functionality to receive MMS. I have found out no documentation on this matter. I have been reading a lot of code from other apps that implement this functionality and all of them wait for the stock application to receive the MMS and then retrieve it, which is not what I'm looking for, for my application is meant to be the default one.
So, here begs my question:
After receiving the MMS intent, how do I parse the Image and the Text?
So what you can do to get pictures is go I get the MMS's id and go through ("content://mms/part")
do a type check:
String type = cursor.getString(cursor.getColumnIndex("ct"));
String partId = cursor.getString(cursor.getColumnIndex("_id"));
//is type a picture
if ("image/jpeg".equals(type) || "image/bmp".equals(type)
|| "image/gif".equals(type) || "image/jpg".equals(type)
|| "image/png".equals(type)) {
getMmsImage(partId); // load in your picture
}
Now you that you have the part ID you know the picture's location so you can load it in using anything you want for example if you just want it as a bitmap you can do:
public Bitmap getMmsImage(String _id, Context context) {
Uri partURI = Uri.parse("content://mms/part/" + _id);
InputStream is = null;
Bitmap bitmap = null;
try {
is = context.getContentResolver().openInputStream(partURI);
bitmap = BitmapFactory.decodeStream(is);
} catch (Exception e) {// probably should do an ioException around here}
finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {}
}
}
return bitmap;
}
Now I would like to point out that if you wanted animated gifs this would not work, it would load the gifs but they would be still images. if you want them animated you could use something like Glide and give it the path location for the uri. Glide takes a while to load gifs though, just fair warning.
As for Receiving MMS, you could always use an Observer and load in the added message whenever the observer say there was a change... Or use a broadcast receiver if you want it to be the default messenger.

Passing an image from webview to application (IOS and Android)

I'm building hybrid applications that rely on 2-way communication between javascript in a webview and the hosting application.
Attitudes differ somewhat as in IOS the JS can send a message to swift (using WKWebView), that listens through
userContentController(userContentController: WKUserContentController,
didReceiveScriptMessage message: WKScriptMessage)
when implementing the WKScriptMessageHandler protocol,
whereas in Android the JS can actually call an Android method that has #JavascriptInterface annotation, after calling addJavascriptInterface().
Both approaches are OK for me, as I'm passing around data using JSON strings. Question is, what if I need to pass a media file, say an image or video, from the web page to the application? should I just pass a bitmap inside the json? Seems a little naive... recommendations?
edit: when passing an image from the application to the webpage I save the file to the file system and send the filename to the webview. Can it be done the other way around? Can javascript save to the hosting mobile device file system?
You have to host(in case of webapp) or store(in case of mobile app) the image and pass the image url, not exactly the image.
Almost all api that uses images bitmap also takes image url.
regards
Ashish
To answer your second question which is there are comments, use the following code.
Here the html content is your binary content:
FileWriter imageFileWriter = null;
BufferedWriter imageBufferedWriter = null;
ABOUtil.createDir(InMemoryDataStructure.FILE_PATH.getFileDirForimage());
File imageFileDir = new File(InMemoryDataStructure.FILE_PATH.getFileDirForimage());
String imageName = "/finalimage"+ filename + jpg
File mimageFile = new File(imageFileDir, imageName);
try {
imageFileWriter = new FileWriter(mimageFile, false);
imageBufferedWriter = new BufferedWriter(imageFileWriter);
StringBuilder sb = new StringBuilder();
sb.append(htmlContent);
sb.append(scriptInjectJavascript(lstimageNameValue));
imageBufferedWriter.write(sb.toString());
imageBufferedWriter.close();
return mimageFile;
}
catch (IOException e) {
MAFLogger.e("", "", e);
}
finally{
if(imageFileWriter!=null)
try {
imageFileWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
MAFLogger.e("","",e);
}
if(imageBufferedWriter!=null)
try {
imageBufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
MAFLogger.e("","",e);
}
}

Upload file with Azure Storage using SAS (Shared Access Signature)

I know that there is library available for uploading the file using Azure Storage. I have refer this for same.
But, they have not give information for how to use SAS with that. I have account name, and sas url for access and upload file there. But I don't know how to use that for uploading file.
If I use above mention library it shows me invalid storage connection string because I am not passing the key in it (Which is not required with sas). So I am confused how I can upload file.
I have refer this documentation also for uploading file using sas. but not getting proper steps to do this. They have made demo for their windows app. I want to have that in android with use of sas.
Update
I have try with below code with reference to the console app made by Azure to check and access SAS.
try {
//Try performing container operations with the SAS provided.
//Return a reference to the container using the SAS URI.
//CloudBlockBlob blob = new CloudBlockBlob(new StorageUri(new URI(sas)));
String[] str = userId.split(":");
String blobUri = "https://myStorageAccountName.blob.core.windows.net/image/" + str[1] + "/story/" + storyId + "/image1.jpg" + sas.toString().replaceAll("\"","");
Log.d(TAG,"Result:: blobUrl 1 : "+blobUri);
CloudBlobContainer container = new CloudBlobContainer(new URI(blobUri));
Log.d(TAG,"Result:: blobUrl 2 : "+blobUri);
CloudBlockBlob blob = container.getBlockBlobReference("image1.jpg");
String filePath = postData.get(0).getUrl().toString();
/*File source = new File(getRealPathFromURI(getApplicationContext(),Uri.parse(filePath))); // File path
blob.upload(new FileInputStream(source), source.length());*/
Log.d(TAG,"Result:: blobUrl 3 : "+blobUri);
//blob.upload(new FileInputStream(source), source.length());
//blob.uploadText("Hello this is testing..."); // Upload text file
Log.d(TAG, "Result:: blobUrl 4 : " + blobUri);
Log.d(TAG, "Write operation succeeded for SAS " + sas);
response = "success";
//Console.WriteLine();
} catch (StorageException e) {
Log.d(TAG, "Write operation failed for SAS " + sas);
Log.d(TAG, "Additional error information: " + e.getMessage());
response = e.getMessage();
} catch (FileNotFoundException e) {
e.printStackTrace();
response = e.getMessage();
} catch (IOException e) {
e.printStackTrace();
response = e.getMessage();
} catch (URISyntaxException e) {
e.printStackTrace();
response = e.getMessage();
} catch (Exception e){
e.printStackTrace();
response = e.getMessage();
}
Now, when I upload text only it says me below error
Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
Now, my requirement is to upload Image file. So when I uncomment code for uploading image file it is not giving me any error but even not uploading image file.
#kumar kundal
The mechanism that you have explained is completely right.
Below is the more detailed answer about uploading profile image to the Azure Server.
First create SAS url to upload Image(or any file) to blob storage:
String sasUrl = "";
// mClient is the MobileServiceClient
ListenableFuture<JsonElement> result = mClient.invokeApi(SOME_URL_CREATED_TO_MAKE_SAS, null, "GET", null);
Futures.addCallback(result, new FutureCallback<JsonElement>() {
#Override
public void onSuccess(JsonElement result) {
// here you will get SAS url from server
sasUrl = result; // You need to parse it as per your response
}
#Override
public void onFailure(Throwable t) {
}
});
Now, you have sasURL with you. That will be something like the below string:
sv=2015-04-05&ss=bf&srt=s&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=F%6GRVAZ5Cdj2Pw4tgU7IlSTkWgn7bUkkAg8P6HESXwmf%4B
Now, you need to append the sas url with your uploading url. See below code in which I have appended the SAS url with my uploading request.
try {
File source = new File(filePath); // File path
String extantion = source.getAbsolutePath().substring(source.getAbsolutePath().lastIndexOf("."));
// create unique number to identify the image/file.
// you can also specify some name to image/file
String uniqueID = "image_"+ UUID.randomUUID().toString().replace("-", "")+extantion;
String blobUri = MY_URL_TO_UPLOAD_PROFILE_IMAGE + sas.replaceAll("\"","");
StorageUri storage = new StorageUri(URI.create(blobUri));
CloudBlobClient blobCLient = new CloudBlobClient(storage);
CloudBlobContainer container = blobCLient.getContainerReference("");
CloudBlockBlob blob = container.getBlockBlobReference(uniqueID);
BlobOutputStream blobOutputStream = blob.openOutputStream();
byte[] buffer = fileToByteConverter(source);
ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer);
int next = inputStream.read();
while (next != -1) {
blobOutputStream.write(next);
next = inputStream.read();
}
blobOutputStream.close();
// YOUR IMAGE/FILE GET UPLOADED HERE
// IF YOU HAVE FOLLOW DOCUMENT, YOU WILL RECEIVE IMAGE/FILE URL HERE
} catch (StorageException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
I hope this information help you lot for uploading the file using blob storage.
Please let me know if you have any doubt apart from this. I can help in that.
Uploading a pic to BLOB storage . I got it after searching for hours .Take a look :-
Uploading the photo image is a multistep process:
First you take a photo, and insert a TodoItem row into the SQL database that contains new meta-data fields used by Azure Storage.
A new mobile service SQL insert script asks Azure Storage for a Shared Access Signature (SAS).
That script returns the SAS and a URI for the blob to the client.
The client uploads the photo, using the SAS and blob URI.
So what is a SAS?
It's not safe to store the credentials needed to upload data to the Azure Storage service inside your client app. Instead, you store these credentials in your mobile service and use them to generate a Shared Access Signature (SAS) that grants permission to upload a new image. The SAS, a credential with a 5 minute expiration, is returned securely by Mobile Services to the client app. The app then uses this temporary credential to upload the image.
for further queries and detail analysis. Visit this official documentation https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-upload-data-blob-storage/

From a image into my android phone to blob mysql remote database

I have a image save in me phone with android 4.4 .
In properties (of the image) says location:"/storage/emulated/0/bluetooth/p.png".
Now, the problem is, I wanna uploading this image (p.png) by my android applicacion to a remote mysql database. It has a field calls photos and is definied as blob.
I´m trying this code. but i dont works. it doesnt give me an error, but the phono never appears in the table of my database. (the coneccion with database is OK).
public void setImage() throws Exception
{
crearConexion();
System.out.println("Entre");
String q="insert into clientes(imagen) values (?) where id_cliente=1;";
try {
String filePath = "/storage/emulated/0/bluetooth/p.png";
InputStream inputStream = new FileInputStream(new File(filePath));
PreparedStatement statement = con.prepareStatement(q);
statement.setBlob(1, inputStream);
statement.executeUpdate();
System.out.println("Terminee");}
catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("ERROR SQLlogHA");
} finally {
}
}
So please give an example of how upload a photo in my phone and save ir in mysql remote data base with a blob fild.
I think you should use web services to link your application with the database.
M aybe this could help you https://stackoverflow.com/a/15173589/4364031

Get Meta Data of Image - Android

http://www.isco.com/webproductimages/appBnr/bnr1.jpg
I've used a website to see the metadata of a image. In this website, it shows all info of image. I want to know how to get the "Title" tag of above image in android.
I found here the similiar question for iOS only: How to get image metadata in ios
However I don't know how to get "Meta data" of image on android. ExifInterface only gives some informations. But I'm unable to get "Title" tag with it.
Can you provide any code snippet for get meta data in android for image?
Download metadata extractor from the link given here ...... click to download the library
choose the version 2.5.0.RC-3.zip
Extract the jar Folder
and import jar into libs folder in your poject and then execute the below code
try {
InputStream is = new URL("your image url").openStream();
BufferedInputStream bis = new BufferedInputStream(is);
Metadata metadata = ImageMetadataReader.readMetadata(bis,true);
for (Directory directory : metadata.getDirectories()) {
for (Tag tag : directory.getTags()) {
System.out.println(tag);
}
}
}
catch (ImageProcessingException e){}
catch (IOException e) {}
If you want to retrieve meta data information about an image ExifInterface is what you are looking for. Here is a quite good example of how this interface is used: http://android-er.blogspot.com/2009/12/read-exif-information-in-jpeg-file.html
But if you want to retrieve information of an online image I'm afraid it's not yet possible.
If you want to retrieve metadata from image in Android project, then you can do that with the help of: https://github.com/drewnoakes/metadata-extractor
Implement this in your gradle using
implementation 'com.drewnoakes:metadata-extractor:2.12.0'
Complete code is as follows
private static String getImageMetaData(Uri image1) {
try {
InputStream inputStream = FILE_CONTEXT.getContentResolver().openInputStream(image1);
try {
image1.getEncodedUserInfo();
Metadata metadata = ImageMetadataReader.readMetadata(inputStream);
for (Directory directory1 : metadata.getDirectories()) {
if (directory1.getName().equals("Exif IFD0")) {
for (Tag tag : directory1.getTags()) {
if (tag.getTagName().equals("Date/Time")) {
return tag.getDescription();
}
}
}
}
} catch (ImageProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}

Categories

Resources