Upload chunked video to Twitter with spring-social-twitter / postman - java

I am currently trying to build an application to post videos to Twitter on behalf of a user.
So I currently have the application-key, application-secret, access-token and access-secret.
final TwitterTemplate twitterTemplate = new TwitterTemplate(
"application-key",
"application-secret",
"access-token",
"access-secret");
So using this I can actually post a tweet containing only text.
If I want to include an image I have to include the workaround "solution" posted on a bug of spring-social-twitter. This resolves the image but the video still cannot be uploaded.
So the rational thinking was to try out this upload with postman to "isolate" the call itself.
In the previous image we can see the Authorization process. This is the same for Every single call I make.
with this Auth a simple POST to https://api.twitter.com/1.1/statuses/update.json?status=hello works. Same with 2 calls for image.
POST to https://upload.twitter.com/1.1/media/upload.json?media_category=tweet_image for the image upload ( body -> media : image ).
POST to https://api.twitter.com/1.1/statuses/update.json merge the media_id with a new tweet.
But back to the video following again the official guide of twitter when I send this
the response is
when the request media_type does not contain / then a valid response will return from tweeter with a media_id, lets call it X.
So I append a video ( second command ) on X and then finalize the video ( third command ) on X. But as expected the response is
as the media_type was never provided. On the other hand if the video on the second step is pushed as base64 encoded ( and including the header for base64 encoding) then a response of
No matter what I have done so far I cannot make it post a video. I even used Postman as a proxy for twurl and captured the request of twurl that did upload the video. Changed the auth with mine ( because of nonce it requires to be recreated ) and the request failed to upload the video!
some notes :
the credentials are up to dates and work from twurl.
the video is valid and can be uploaded from both tweeter ui and twurl upload command.
the base64 convert was encoded / decoded with linux base64 tool piped to file and validated that the size is the same.
If any other clarification is required please let me know!
Thank you in advance

I know it's late but in case someone has same question,
to upload video on twitter you have to use chunked-media-upload method.
here's the reference
https://developer.twitter.com/en/docs/media/upload-media/uploading-media/chunked-media-upload

Related

JAVA youtube api allow users to upload to my channel without login

I was playing around with youtube api samples that they provide in this link
with JAVA
I can search for videos upload videos to specific channel and all the code that they provide works fine.
the only problem I face is "when I try to upload it opens my default browser and asks me to sign in"
like this screenshot.
here is what in my head I know it's not that simple it's just a imagination of what I want to achieve.
// String myaccount = "username#gmail.com"
// String mypassword = "123456789"
// String mychannel_id = "UCU7mv98lde1hon2DXIgGMKg"
// signin(myaccount,mypassword,mychannel_id);
// upload(video.mp4);
what I have:
client_id, client_secret in json file
the channel id, account, and the password
i was searching for about a day and all i got is ..
access token
,Token Service API
,identity toolkit api
,onBehalfOfContent,onBehalfOfContentOwner
however I don't know how they work or where I can get them
finally I have small idea I traced the code and I found it saves a file with all credentials in C://users/user-name/.oauth-credentials
it's not readable but it seems like it is used to authorize the account with the password and channel id
can I use this?
would it expire for any reason and i have to refresh and if so how can I refresh it?
thanks for help BTW

Where If-Match header comes from?

I have progressive download streaming in my Java application and I am using popular MultipartFileSender by Kevin to serve the video: https://gist.github.com/davinkevin/b97e39d7ce89198774b4#file-multipartfilesender on the back-end and video.js on the front-end.
In this file sender there is code where If-Match header is checked and if it doesn't match ETag (filename) the error is sent in the response.
String ifMatch = request.getHeader("If-Match");
if (ifMatch != null && !HttpUtils.matches(ifMatch, fileName)) {
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
return;
}
Here is my problem:
Let say I uploaded file into the system and opened the page with HTML5 video playback - everything is good here, video playback works. Then, I have replaced video file with another one - the file is stored with different unique file name (internal logic). After this, when I open video page again the new video file is retrieved on the back-end with new file name, however browser still sends If-Match header with old file name, so mismatch appears: new_file_name != If-Match header's value.
I wasn't able to figure out why browser sends deprecated value in If-Match header. Could you please point me out where If-Match header comes from? I didn't find any info regarding video.js sending it or regarding adding this by tomcat server.

Can I save images to Blobstore and save data to Datastore in one trip?

The argument has been made and settled on numerous occasions: Blobstore is better than DataStore for storing images. Now say I have an app similar to Instagram or Facebook or Yelp or any of those apps that are image intensive. In my particular case the ideal model would be
public class IdealPostModel{
Integer userId;
String synopsys;
Blob image;
...//more data/fields about the post
}
But since I must use the BlobStore, my model does not have a blob but instead a URL or BlobKey. The heavy catch is that to send a post (i.e. save a post to server) the app must -- in that order --
Send all the non-blob data to the server.
Wait for server to respond with BlobstoreUtils.generateServingUrl(null) data
Send the images to the BlobStore
Have BlobStore send response to my server with the BlobKey or url of the image
Store the BlobKey/url in my DataStore entity
That's a lot of handshakes!!!
Is there a way to send all the data to the server in step one: strings and image. And then from there have the server do everything else? Of course I am here hoping to reduce the amount of work. I image App Engine must be quite mature by now and there has to be a simpler way than my architecture.
Now of course I am here because I am experiencing situations where the data is saved but the BlobKey or URL is not being saved to the Entity. It happens about 10% of the time. Or maybe less, but it does feel like 10%. It's driving my users insane, which means it's driving me even more insane since I don't want to lose my users.
Ideally
App sends everything to server in one call: image and metadata such as userId and synopsys
Server somehow gets a blob key from Blobstore
Server sends image to blobstore, to be stored at the provided blob key, and server sends other data to DataStore, also including the blob key in the datastore.
Update
public static String generateServingUrl(String path) {
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
return blobstoreService.createUploadUrl(null == path ? "/upload" : path);
}
This is a snippet on my server.
The workflow is different. Given your example:
There is "Post" button and "Attach an image" button under a form for a new post.
When a user hits the Attach button, you ask a user to select a file and save it to the BlobStore (or Google Cloud Storage). There is no need to call BlobstoreUtils.generateServingUrl(null) - you need to get an upload URL. When a call returns a key, you store it in the Post object.
When a user hits the Post button, you save the Post - including the image key (keys) in the Datastore. Thus, the entire workflow takes only two calls.
If a user hits the Cancel button - remember to delete the uploaded image(s) if any, or they will be orphaned. The tricky part is to delete these images if a user simply left your app or lost connection.
If you want, you can reverse the process - save post first, then let users attach images. This is not what most users expect, but it solves the problem with orphaned images.
You actually cand send everything in a single request.
Bear in mind that when you send a blob using a URL gotten by calling blobstoreService.createUploadUrl("/yourservingurl") , GAE actually makes a first request to a different URL, stores the blob and then calls /yourservingurl passing you the blobkeys which you can retrive by doing:
Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
List<BlobKey> blobKeys = blobs.get("myFile");
So in effect all other form values will be lost after that first request, BUT if you can build that URL dynamically eg
blobstoreService.createUploadUrl("/yourservingurl?param1=a&param2=b")
then you can get back those parameters on your Servlet and persist everything (including the blobkey of the already stored blob) at once, making much fewer calls to the datastore.
UPDATE:
the steps would be
1) Gather all parameters on the client side and create an upload URL with those params eg: blobstoreService.createUploadUrl("/yourservingurl?userId=989787") . GAE will generate a unique URL for that specific request.
when you commit the form, GAE will persist the blobs and call /yourservingurl
2) On the Servlet serving /yourservingurl you'll get all the blobkeys form files you uploaded by using : blobstoreService.getUploads(request) AND you can get the parameters you included with the standard request.getParameter("userId")
3) Now in your servlet you have all the parameters (eg userId) you sent plus the blobkey, you can persist your Post object in one call.

uploading png to server with java using POST data

Hi ive been having some trouble trying to transfer a png image to my webserver using java and php Ive tried using FTP but the software that Im scripting for blocks port 21 rendering it useless
I was directed to use form urlencoded data then use a POST request to get it
im completely lost on this topic and could just use some direction apparently file and image hosting sites use the same method to transfer files and images from the users computer to their servers.
maybe just an explanation of whats going on might help so that I can grasp what exactly im trying to do with java and php
Any help would be much appreciated!
I've also been facing the same kind of problem a short time ago.
After some researches, I found out that the HttpComponents library from Apache (http://hc.apache.org/) contains pretty much everything you'll need to build HTTP-POST request in a quite simple way.
Here is a method that will send a POST request with a file to a certain URL:
public static void upload(URL url, File file) throws IOException, URISyntaxException {
HttpClient client = new DefaultHttpClient(); //The client object which will do the upload
HttpPost httpPost = new HttpPost(url.toURI()); //The POST request to send
FileBody fileB = new FileBody(file);
MultipartEntity request = new MultipartEntity(); //The HTTP entity which will holds the different body parts, here the file
request.addPart("file", fileB);
httpPost.setEntity(request);
HttpResponse response = client.execute(httpPost); //Once the upload is complete (successful or not), the client will return a response given by the server
if(response.getStatusLine().getStatusCode()==200) { //If the code contained in this response equals 200, then the upload is successful (and ready to be processed by the php code)
System.out.println("Upload successful !");
}
}
In order to complete the upload, you must have a php code that handle that POST request,
here it is:
<?php
$directory = 'Set here the directory you want the file to be uploaded to';
$filename = basename($_FILES['file']['name']);
if(strrchr($_FILES['file']['name'], '.')=='.png') {//Check if the actual file extension is PNG, otherwise this could lead to a big security breach
if(move_uploaded_file($_FILES['file']['tmp_name'], $directory. $filename)) { //The file is transfered from its temp directory to the directory we want, and the function returns TRUE if successfull
//Do what you want, SQL insert, logs, etc
}
}
?>
The URL object given to the Java method must point to the php code, like http://mysite.com/upload.php and can be build very simply from a String. The file can also be build from a String representing its path.
I didn't take the time to test it properly, but it was build upon proper working solution, so I hope this will help you.

Server-side verification of Android Market Licensing responses with PHP

I'm building a server to test all my in-app purchases of Android market. But I don't think that I'm sending the information from the app correctly. My server is built in PHP.
My app access the url:
...&response={...json...}&signature={...signature...}
The signature is previously encoded with URLEncoder.encode(signature,"UTF-8")
My server:
$response = $_GET["response"];
$signature = htmlspecialchars(urldecode($_GET["signature"]));
And then I execute the verification process. I think the problem comes from the way that I'm passing the arguments from the app to server, because if I copy the response and signature manually and test them, the verification function says that they are valid.
URL:
...&response={"nonce":-871647007848398655,"orders":[{"orderId":"768142460571407","packageName":"net.xxx.aaa","productId":"net.xxx.mmf.flyboys","purchaseTime":1330090436000,"purchaseState":0,"developerPayload":"Flyboys"},{"orderId":"203523162686707","packageName":"net.xxx.aaa","productId":"net.xxx.mmf.16blocks","purchaseTime":1330511533000,"purchaseState":0,"developerPayload":"16 Blocks"},{"orderId":"328483664834399","packageName":"net.xxx.aaa","productId":"net.xxx.mmf.aceventura3","purchaseTime":1331037005000,"purchaseState":0,"developerPayload":"Ace Ventura 3"}]}&signature=EyT9IgZeq2OLRqCtabTIc5wOKARtdHUfCQAdkEqkGyi%2Bd1qQgcfxPnvIa9VMDQqwh8rxxGPOYQKuhaEuZUJzbSain8%2FN7p41euzb1n1%2FgZkgqXlQTDn076U2AXcp1ymBFZamrwETo0gkZi4q6PZV47oR7Rk28vPU5vjs%2Bl0TN0DdlzclHuH40CkZqD1ErSMMwWGTGR6bGnJlmmhgHC2KV7Ab63i0hdgkqk5MOtkOxhjS%2B4LG1YxmJIsxhJnOcmNI7n2VKUdtn%2B0CWxO5M8m0BcfpZ9Se3sR6ZtVli2rS1KSKQPL1Td9GWPhmG4nvzZFtKCqf9Le6Meudv6iFTSw5Hg%3D%3D
Vardump
Response
string
'{"nonce":-871647007848398655,"orders":[{"orderId":"768142460571407","packageName":"net.xxx.aaa","productId":"net.xxx.mmf.flyboys","purchaseTime":1330090436000,"purchaseState":0,"developerPayload":"Flyboys"},{"orderId":"203523162686707","packageName":"net.xxx.aaa","productId":"net.xxx.mmf.16blocks","purchaseTime":1330511533000,"purchaseState":0,"developerPayload":"16
Blocks"},{"orderId":"328483664834399","packageName":"net.xxx.aaa","productId":"net.xxx'...
(length=617)
Signature
string 'EyT9IgZeq2OLRqCtabTIc5wOKARtdHUfCQAdkEqkGyi
d1qQgcfxPnvIa9VMDQqwh8rxxGPOYQKuhaEuZUJzbSain8/N7p41euzb1n1/gZkgqXlQTDn076U2AXcp1ymBFZamrwETo0gkZi4q6PZV47oR7Rk28vPU5vjs
l0TN0DdlzclHuH40CkZqD1ErSMMwWGTGR6bGnJlmmhgHC2KV7Ab63i0hdgkqk5MOtkOxhjS
4LG1YxmJIsxhJnOcmNI7n2VKUdtn
0CWxO5M8m0BcfpZ9Se3sR6ZtVli2rS1KSKQPL1Td9GWPhmG4nvzZFtKCqf9Le6Meudv6iFTSw5Hg=='
(length=344)
When using URL Encode php will automatic decode data so if your re-decoding it it's going to break something, I have had this problem before
URL encoding is for the browser so stuff like & in a string sent though get does not act as new parameter in GET
so for you code htmlspecialchars(urldecode($_GET["signature"])); should be htmlspecialchars($_GET["signature"]);
I know this has been answered by comments but Added answer for Googlers

Categories