Tuesday, September 27, 2011

[YouTube-API] Youtube Upload Problem on Android

Hello,

I'm using PhoneGap for my Android Application, this app requires me to upload videos to youtube and Facebook, I did successfully on iPhone.. but in the case of Android the Facebook succeed but not the youtube it..



$.ajax("http://gdata.youtube.com/action/GetUploadToken",
                        {
                            type : "POST",
                            beforeSend : function(jqXHR) {
                              
                                jqXHR.setRequestHeader("Authorization", "OAuth " + OAUTH VALUE I GOT);
                                jqXHR.setRequestHeader("GData-Version", "2");
                                jqXHR.setRequestHeader("X-GData-Key", "key=\"AI39si6pUBZk4BwA84Wut00mmSTmaYDZXdfaYnn78rlX8sJYPtVwZwPJL89tOIRt2foFLoynb8l2m3Bd0x6C5mqEeQcN8uhOgg\"");
                                return jqXHR;
                            },
                            success : function(data, textStatus, jqXHR) {
                                console.log("Youtube upload token success");
                                console.log("data: " + data);
                                console.log("textStatus: " + textStatus);
                              alert('Completed');
                                OPS.Events.dispatchEvent(myClipsAuxChange);
                                $xml = $(jqXHR.responseXML);
                                $url = $xml.find("url");
                                console.log("$url.text(): " + $url.text());
                                $token = $xml.find("token");
                                console.log("$token.text(): " + $token.text());
                                var upURL = $url.text();
                                var upToken = $token.text();
                                console.log("Passed text setting");
                               
                                window.plugins.fileUploader.upload(upURL + "?nexturl=http%3A%2F%2Fm.youtube.com%2Fterms", videoPath, {"token":upToken}, "test", "test.mp4", "video/mp4",
                                    function(result){
                                        console.log("Done: " + result);
                                           alert('Success');
                                           OPS.Events.dispatchEvent(myClipsAuxChange);
                                    },
                                    function(result){
                                        console.log("Error: " + result);
                                           alert('Failure');
                                           OPS.Events.dispatchEvent(myClipsAuxChange);
                                    },
                                    function(loaded,total){
                                        var percent = .01 * total * loaded;
                                           console.log(loaded);
                                           console.log(total);
                                           console.log("Uploaded " + percent);
                                });
                                console.log("passed fileUploader()");
                            },
                            error : function(jqXHR, textStatus, errorThrown) {
                                console.log("Youtube upload failure");
                                console.log("textStatus: " + textStatus);
                                console.log("errorThrown: " + errorThrown);
                                console.log("getResponseHeaders: " + jqXHR.getAllResponseHeaders());
                            },
                            data : '<?xml version="1.0"?><entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007"><media:group><media:title type="plain">'+$("#ytTitle").val()+'</media:title><media:description type="plain">'+$("#ytDescription").val()+'</media:description><media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">People</media:category><media:keywords>percyfx, custom, clip</media:keywords></media:group></entry>',
                            contentType : "application/atom+xml; charset=utf-8"
                           
                        }
                );



The Android Plugin code follows



import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URLEncoder;

import android.net.Uri;
import java.net.URL;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
import android.webkit.CookieManager;

import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;

/**
* @author matt
*
*/
public class FileUploader extends Plugin {

    /* (non-Javadoc)
    * @see com.phonegap.api.Plugin#execute(java.lang.String, org.json.JSONArray, java.lang.String)
    */
    @Override
    public PluginResult execute(String action, JSONArray args, String callbackId) {
               
        try {
            String server = args.getString(0);
            String file = args.getString(1);
            JSONObject params = args.getJSONObject(2);
           
            String fileKey = "file";
            String fileName = "image.jpg";
            String mimeType = "image/jpeg";
            if(args.length() > 3) {
                fileKey = args.getString(3);
            }
            if(args.length() > 4) {
                fileName = args.getString(4);
            }
            if(args.length() > 5) {
                mimeType = args.getString(5);
            }
           
            if (action.equals("upload")) {
                upload(file, server, params, fileKey, fileName, mimeType, callbackId);
            } else if (action.equals("uploadByUri")) {
                Uri uri = Uri.parse(file);
                upload(uri, server, params, fileKey, fileName, mimeType, callbackId);
            } else {
                return new PluginResult(PluginResult.Status.INVALID_ACTION);
            }
            PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
            r.setKeepCallback(true);
            return r;
        } catch (JSONException e) {
            e.printStackTrace();
            return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
        }

    }
   
    public void upload(Uri uri, String server, JSONObject params, final String fileKey, final String fileName, final String mimeType, String callbackId) {
        try {
            InputStream fileInputStream=this.ctx.getContentResolver().openInputStream(uri);
            upload(fileInputStream, server, params, fileKey, fileName, mimeType, callbackId);
        } catch (FileNotFoundException e) {
            Log.e("PhoneGapLog", "error: " + e.getMessage(), e);
        }
    }

    public void upload(String filename, String server, JSONObject params, final String fileKey, final String fileName, final String mimeType, String callbackId) {
        File uploadFile = new File(filename);
        try {
            FileInputStream fileInputStream = new FileInputStream(uploadFile);
            upload(fileInputStream, server, params, fileKey, fileName, mimeType, callbackId);
        } catch (FileNotFoundException e) {
            Log.e("PhoneGapLog", "error: " + e.getMessage(), e);
        }

    }
   
   
    public void upload(InputStream fileInputStream, String server, JSONObject params, final String fileKey, final String fileName, final String mimeType, final String callbackId) {
        try {
           
            System.out.println("RRR::");

            String lineEnd = "\r\n";
            String td = "--";
            String boundary = "*****com.a3mn.percyfx";
           
            URL url = new URL(server);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
           
//            Get cookies that have been set in our webview
            CookieManager cm = CookieManager.getInstance();
            String cookie = cm.getCookie(server);
           
            // allow inputs
            conn.setDoInput(true);
            // allow outputs
            conn.setDoOutput(true);
            // don't use a cached copy
            conn.setUseCaches(false);
            // use a post method
            conn.setRequestMethod("POST");
            // set post headers
            conn.setRequestProperty("Connection","Keep-Alive");
            conn.setRequestProperty("Content-Type","multipart/form-data;boundary="+boundary);
            conn.setRequestProperty("Cookie", cookie);
            // open data output stream
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
           
            try {
                System.out.println("RRR1::");
                for (Iterator iter = params.keys(); iter.hasNext();) {
                    Object key = iter.next();
                    dos.writeBytes(URLEncoder.encode(td + boundary + lineEnd, "UTF-8"));
                    dos.writeBytes(URLEncoder.encode("Content-Disposition: form-data; name=\"" +  key + "\"; ", "UTF-8"));
                    dos.writeBytes(URLEncoder.encode(lineEnd + lineEnd, "UTF-8"));
                    dos.writeBytes(URLEncoder.encode(params.getString(key.toString()), "UTF-8"));
                    dos.writeBytes(URLEncoder.encode(lineEnd, "UTF-8"));
                }
            } catch (JSONException e) {
                Log.e("PhoneGapLog", "error: " + e.getMessage(), e);
            }

           
            dos.writeBytes(URLEncoder.encode(td + boundary + lineEnd, "UTF-8"));
            dos.writeBytes(URLEncoder.encode("Content-Disposition: form-data; name=\"" + fileKey + "\";filename=\"" + fileName + "\"" + lineEnd, "UTF-8"));
            dos.writeBytes(URLEncoder.encode("Content-Type: " + mimeType + lineEnd, "UTF-8"));
           
            dos.writeBytes(URLEncoder.encode(lineEnd, "UTF-8"));
            // create a buffer of maximum size
            int bytesAvailable = fileInputStream.available();
            final int total = bytesAvailable;
            Log.e("PhoneGapLog", "available: " + bytesAvailable);

            int maxBufferSize = 1024;
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);
            byte[] buffer = new byte[bufferSize];
            // read file and write it into form...
            int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            int progress = bytesRead;
            int send = 0;
            while (bytesRead > 0)
            {
                dos.write(buffer, 0, bufferSize);
                dos.flush();
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                progress += bytesRead;
                final int prog = progress;
                Log.e("PhoneGapLog", "read " + progress + " of " + total);
               
//                Sending every progress event is overkill
                if (send++ % 20 == 0) {
                    ctx.runOnUiThread(new Runnable () {
                    public void run() {
                        try {
                            JSONObject result = new JSONObject();
                            System.out.println("RRR:: "+FileUploader.Status.PROGRESS);
                            result.put("status", FileUploader.Status.PROGRESS);
                            result.put("progress", prog);
                            result.put("total", total);
                            PluginResult progressResult = new PluginResult(PluginResult.Status.OK, result);
                            progressResult.setKeepCallback(true);
                            success(progressResult, callbackId);
                        } catch (JSONException e) {
                            Log.e("PhoneGapLog", "error: " + e.getMessage(), e);
                        }
                    }
                });
//                    Give a chance for the progress to be sent to javascript
                Thread.sleep(100);
                }
            }
            // send multipart form data necessary after file data...
            dos.writeBytes(URLEncoder.encode(lineEnd, "UTF-8"));
            dos.writeBytes(URLEncoder.encode(td + boundary + td + lineEnd, "UTF-8"));

            // close streams
            fileInputStream.close();
            dos.flush();
            dos.close();
           
            JSONObject result = new JSONObject();
            result.put("status", FileUploader.Status.COMPLETE);
            System.out.println("Upload Completed");
            result.put("progress", progress);
            result.put("total", total);

            InputStream is = conn.getInputStream();
            int ch;
            StringBuffer b =new StringBuffer();
            while( ( ch = is.read() ) != -1 ) {
                b.append( (char)ch );
            }
           
            String s=b.toString();
             
           
            result.put("result", s);
            PluginResult progressResult = new PluginResult(PluginResult.Status.OK, result);
            progressResult.setKeepCallback(true);
            success(progressResult, callbackId);

        }
        catch (MalformedURLException e) {
             Log.e("PhoneGapLog", "error: " + e.getMessage(), e);
             PluginResult result = new PluginResult(PluginResult.Status.MALFORMED_URL_EXCEPTION, e.getMessage());
             error(result, callbackId);
        }
        catch (FileNotFoundException e) {
             Log.e("PhoneGapLog", "error: " + e.getMessage(), e);
             e.printStackTrace();
             PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.getMessage());
             error(result, callbackId);
        }
        catch (IOException e) {
             Log.e("PhoneGapLog", "error: " + e.getMessage(), e);
             PluginResult result = new PluginResult(PluginResult.Status.IO_EXCEPTION, e.getMessage());
             error(result, callbackId);
        } catch (InterruptedException e) {
             Log.e("PhoneGapLog", "error: " + e.getMessage(), e);
             PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.getMessage());
             error(result, callbackId);
        } catch (JSONException e) {
             Log.e("PhoneGapLog", "error: " + e.getMessage(), e);
             PluginResult result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage());
             error(result, callbackId);
        }
    }
   
    public enum Status {
        PROGRESS,
        COMPLETE
    }


}



The conn.getInputStream() throws File not found exception... but the same code I'm using for Facebook works fine.. Can anyone help me...?


The error I found as follows

09-27 14:22:41.546: ERROR/PhoneGapLog(12128): java.io.FileNotFoundException: http://uploads.gdata.youtube.com/action/FormDataUpload/AIwbFATeYpniedtIjOQOuqt5ZL4jFuT6XPXWQ6nVEtk2Llz4dLAy_9QoWNA6kijX0Cko5PF-evAJYDEpUavIgU428vAQ5a6mdxLvcffH-YqOSScBXLFHTlnVz1VjisO78PrtBehyi-MJ?nexturl=http%3A%2F%2Fm.youtube.com%2Fterms
09-27 14:22:41.546: ERROR/PhoneGapLog(12128):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:1162)
09-27 14:22:41.546: ERROR/PhoneGapLog(12128):     at com.a3mn.percyfx.FileUploader.upload(FileUploader.java:207)
09-27 14:22:41.546: ERROR/PhoneGapLog(12128):     at com.a3mn.percyfx.FileUploader.upload(FileUploader.java:88)
09-27 14:22:41.546: ERROR/PhoneGapLog(12128):     at com.a3mn.percyfx.FileUploader.execute(FileUploader.java:58)
09-27 14:22:41.546: ERROR/PhoneGapLog(12128):     at com.phonegap.api.PluginManager$1.run(PluginManager.java:86)
09-27 14:22:41.546: ERROR/PhoneGapLog(12128):     at java.lang.Thread.run(Thread.java:1096)
09-27 14:22:41.546: WARN/System.err(12128): java.io.FileNotFoundException: http://uploads.gdata.youtube.com/action/FormDataUpload/AIwbFATeYpniedtIjOQOuqt5ZL4jFuT6XPXWQ6nVEtk2Llz4dLAy_9QoWNA6kijX0Cko5PF-evAJYDEpUavIgU428vAQ5a6mdxLvcffH-YqOSScBXLFHTlnVz1VjisO78PrtBehyi-MJ?nexturl=http%3A%2F%2Fm.youtube.com%2Fterms
09-27 14:22:41.546: WARN/System.err(12128):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:1162)
09-27 14:22:41.546: WARN/System.err(12128):     at com.a3mn.percyfx.FileUploader.upload(FileUploader.java:207)
09-27 14:22:41.546: WARN/System.err(12128):     at com.a3mn.percyfx.FileUploader.upload(FileUploader.java:88)
09-27 14:22:41.546: WARN/System.err(12128):     at com.a3mn.percyfx.FileUploader.execute(FileUploader.java:58)
09-27 14:22:41.546: WARN/System.err(12128):     at com.phonegap.api.PluginManager$1.run(PluginManager.java:86)
09-27 14:22:41.546: WARN/System.err(12128):     at java.lang.Thread.run(Thread.java:1096)



Thanks & Regards,
Ramkumar Murugadoss

--
You received this message because you are subscribed to the Google Groups "YouTube APIs Developer Forum" group.
To view this discussion on the web visit https://groups.google.com/d/msg/youtube-api-gdata/-/Uf9I1jIalQEJ.
To post to this group, send email to youtube-api-gdata@googlegroups.com.
To unsubscribe from this group, send email to youtube-api-gdata+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/youtube-api-gdata?hl=en.

No comments:

Post a Comment