pritishvaidya

vimeo upload

Oct 18th, 2016
462
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.95 KB | None | 0 0
  1. package test;
  2.  
  3. import com.kentcdodds.javahelper.helpers.PrinterHelper;
  4. import java.io.*;
  5. import java.util.ArrayList;
  6. import java.util.Arrays;
  7. import java.util.List;
  8. import javax.swing.JOptionPane;
  9. import javax.xml.parsers.DocumentBuilder;
  10. import javax.xml.parsers.DocumentBuilderFactory;
  11. import org.scribe.builder.ServiceBuilder;
  12. import org.scribe.builder.api.VimeoApi;
  13. import org.scribe.exceptions.OAuthException;
  14. import org.scribe.model.*;
  15. import org.scribe.oauth.OAuthService;
  16. import org.w3c.dom.Document;
  17. import org.w3c.dom.Element;
  18. import org.xml.sax.InputSource;
  19.  
  20. public class VimeoTest {
  21.  
  22.   private static OAuthService service;
  23.   private static Token accessToken;
  24.   private static String fileLocation = "C:/test.mp4";
  25.   private static String newline = System.getProperty("line.separator");
  26.   private static int bufferSize = 1048576; // 1 MB = 1048576 bytes
  27.  
  28.   public static void main(String[] args) throws Exception {
  29.     // Replace these with your own api key and secret
  30.  
  31.     String apiKey = "your_api_key"; //Give your own API Key
  32.     String apiSecret = "your_api_secret"; //Give your own API Secret
  33.     String vimeoAPIURL = "http://vimeo.com/api/rest/v2";
  34.     service = new ServiceBuilder().provider(VimeoApi.class).apiKey(apiKey).apiSecret(apiSecret).build();
  35.  
  36.     OAuthRequest request;
  37.     Response response;
  38.  
  39.     accessToken = new Token("your_token", "your_token's_secret"); //Copy the new token you get here
  40.  
  41.     accessToken = checkToken(vimeoAPIURL, accessToken, service);
  42.     if (accessToken == null) {
  43.       return;
  44.     }
  45.  
  46.     // Get Quota
  47.     request = new OAuthRequest(Verb.GET, vimeoAPIURL);
  48.     request.addQuerystringParameter("method", "vimeo.videos.upload.getQuota");
  49.     signAndSendToVimeo(request, "getQuota", true);
  50.  
  51.     // Get Ticket
  52.     request = new OAuthRequest(Verb.GET, vimeoAPIURL);
  53.     request.addQuerystringParameter("method", "vimeo.videos.upload.getTicket");
  54.     request.addQuerystringParameter("upload_method", "streaming");
  55.     response = signAndSendToVimeo(request, "getTicket", true);
  56.  
  57.     // Get Endpoint and ticket ID
  58.     System.out.println(newline + newline + "We're sending the video for upload!");
  59.     Document doc = readXML(response.getBody());
  60.     Element ticketElement = (Element) doc.getDocumentElement().getElementsByTagName("ticket").item(0);
  61.     String endpoint = ticketElement.getAttribute("endpoint");
  62.     String ticketId = ticketElement.getAttribute("id");
  63.     // Setup File
  64.     File testUp = new File(fileLocation);
  65.     boolean sendVideo = sendVideo(endpoint, testUp);
  66.     if (!sendVideo) {
  67.       throw new Exception("Didn't successfully send the video.");
  68.     }
  69.  
  70.     // Complete Upload
  71.     request = new OAuthRequest(Verb.PUT, vimeoAPIURL);
  72.     request.addQuerystringParameter("method", "vimeo.videos.upload.complete");
  73.     request.addQuerystringParameter("filename", testUp.getName());
  74.     request.addQuerystringParameter("ticket_id", ticketId);
  75.     Response completeResponse = signAndSendToVimeo(request, "complete", true);
  76.  
  77.     //Set video info
  78.     setVimeoVideoInfo(completeResponse, service, accessToken, vimeoAPIURL);
  79.   }
  80.  
  81.   /**
  82.    * Send the video data
  83.    *
  84.    * @return whether the video successfully sent
  85.    */
  86.   private static boolean sendVideo(String endpoint, File file) throws FileNotFoundException, IOException {
  87.     // Setup File
  88.     long contentLength = file.length();
  89.     String contentLengthString = Long.toString(contentLength);
  90.     FileInputStream is = new FileInputStream(file);
  91.     byte[] bytesPortion = new byte[bufferSize];
  92.     int maxAttempts = 5; //This is the maximum attempts that will be given to resend data if the vimeo server doesn't have the right number of bytes for the given portion of the video
  93.     long lastByteOnServer = 0;
  94.     boolean first = false;
  95.     while (is.read(bytesPortion, 0, bufferSize) != -1) {
  96.       lastByteOnServer = prepareAndSendByteChunk(endpoint, contentLengthString, lastByteOnServer, bytesPortion, first, 0, maxAttempts);
  97.       if (lastByteOnServer == -1) {
  98.         return false;
  99.       }
  100.       first = true;
  101. //      getProgressBar().setValue(NumberHelper.getPercentFromTotal(byteNumber, getFileSize()));
  102.     }
  103.     return true;
  104.   }
  105.  
  106.   /**
  107.    * Prepares the given bytes to be sent to Vimeo
  108.    *
  109.    * @param endpoint
  110.    * @param contentLengthString
  111.    * @param lastByteOnServer
  112.    * @param byteChunk
  113.    * @param first
  114.    * @param attempt
  115.    * @param maxAttempts
  116.    * @return number of bytes currently on the server
  117.    * @throws FileNotFoundException
  118.    * @throws IOException
  119.    */
  120.   private static long prepareAndSendByteChunk(String endpoint, String contentLengthString, long lastByteOnServer, byte[] byteChunk, boolean first, int attempt, int maxAttempts) throws FileNotFoundException, IOException {
  121.     if (attempt > maxAttempts) {
  122.       return -1;
  123.     } else if (attempt > 0) {
  124.       System.out.println("Attempt number " + attempt + " for video " + "Test Video");
  125.     }
  126.     long totalBytesShouldBeOnServer = lastByteOnServer + byteChunk.length;
  127.     String contentRange = lastByteOnServer + "-" + totalBytesShouldBeOnServer;
  128.     long bytesOnServer = sendVideoBytes(endpoint, contentLengthString, "video/mp4", contentRange, byteChunk, first);
  129.     if (bytesOnServer != totalBytesShouldBeOnServer) {
  130.       System.err.println(bytesOnServer + " (bytesOnServer)" + " != " + totalBytesShouldBeOnServer + " (totalBytesShouldBeOnServer)");
  131.       long remainingBytes = totalBytesShouldBeOnServer - bytesOnServer;
  132.       int beginning = (int) (byteChunk.length - remainingBytes);
  133.       int ending = (int) byteChunk.length;
  134.       byte[] newByteChunk = Arrays.copyOfRange(byteChunk, beginning, ending);
  135.       return prepareAndSendByteChunk(endpoint, contentLengthString, bytesOnServer, newByteChunk, first, attempt + 1, maxAttempts);
  136.     } else {
  137.       return bytesOnServer;
  138.     }
  139.   }
  140.  
  141.   /**
  142.    * Sends the given bytes to the given endpoint
  143.    *
  144.    * @return the last byte on the server (from verifyUpload(endpoint))
  145.    */
  146.   private static long sendVideoBytes(String endpoint, String contentLength, String fileType, String contentRange, byte[] fileBytes, boolean addContentRange) throws FileNotFoundException, IOException {
  147.     OAuthRequest request = new OAuthRequest(Verb.PUT, endpoint);
  148.     request.addHeader("Content-Length", contentLength);
  149.     request.addHeader("Content-Type", fileType);
  150.     if (addContentRange) {
  151.       request.addHeader("Content-Range", "bytes " + contentRange);
  152.     }
  153.     request.addPayload(fileBytes);
  154.     Response response = signAndSendToVimeo(request, "sendVideo on " + "Test title", false);
  155.     if (response.getCode() != 200 && !response.isSuccessful()) {
  156.       return -1;
  157.     }
  158.     return verifyUpload(endpoint);
  159.   }
  160.  
  161.   /**
  162.    * Verifies the upload and returns whether it's successful
  163.    *
  164.    * @param endpoint to verify upload to
  165.    * @return the last byte on the server
  166.    */
  167.   private static long verifyUpload(String endpoint) {
  168.     // Verify the upload
  169.     OAuthRequest request = new OAuthRequest(Verb.PUT, endpoint);
  170.     request.addHeader("Content-Length", "0");
  171.     request.addHeader("Content-Range", "bytes */*");
  172.     Response response = signAndSendToVimeo(request, "verifyUpload to " + endpoint, true);
  173.     if (response.getCode() != 308 || !response.isSuccessful()) {
  174.       return -1;
  175.     }
  176.     String range = response.getHeader("Range");
  177.     //range = "bytes=0-10485759"
  178.     return Long.parseLong(range.substring(range.lastIndexOf("-") + 1)) + 1;
  179.     //The + 1 at the end is because Vimeo gives you 0-whatever byte where 0 = the first byte
  180.   }
  181.  
  182.   /**
  183.   * Checks the token to make sure it's still valid. If not, it pops up a dialog asking the user to
  184.   * authenticate.
  185.   */
  186.   private static Token checkToken(String vimeoAPIURL, Token vimeoToken, OAuthService vimeoService) {
  187.     if (vimeoToken == null) {
  188.       vimeoToken = getNewToken(vimeoService);
  189.     } else {
  190.       OAuthRequest request = new OAuthRequest(Verb.GET, vimeoAPIURL);
  191.       request.addQuerystringParameter("method", "vimeo.oauth.checkAccessToken");
  192.       Response response = signAndSendToVimeo(request, "checkAccessToken", true);
  193.       if (response.isSuccessful()
  194.               && (response.getCode() != 200 || response.getBody().contains("<err code=\"302\"")
  195.               || response.getBody().contains("<err code=\"401\""))) {
  196.         vimeoToken = getNewToken(vimeoService);
  197.       }
  198.     }
  199.     return vimeoToken;
  200.   }
  201.  
  202.   /**
  203.   * Gets authorization URL, pops up a dialog asking the user to authenticate with the url and the user
  204.   * returns the authorization code
  205.   *
  206.   * @param service
  207.   * @return
  208.   */
  209.   private static Token getNewToken(OAuthService service) {
  210.     // Obtain the Authorization URL
  211.     Token requestToken = service.getRequestToken();
  212.     String authorizationUrl = service.getAuthorizationUrl(requestToken);
  213.     do {
  214.       String code = JOptionPane.showInputDialog("The token for the account (whatever)" + newline
  215.               + "is either not set or is no longer valid." + newline
  216.               + "Please go to the URL below and authorize this application." + newline
  217.               + "Paste the code you're given on top of the URL here and click \'OK\'" + newline
  218.               + "(click the 'x' or input the letter 'q' to cancel." + newline
  219.               + "If you input an invalid code, I'll keep popping up).", authorizationUrl + "&permission=delete");
  220.       if (code == null) {
  221.         return null;
  222.       }
  223.       Verifier verifier = new Verifier(code);
  224.       // Trade the Request Token and Verfier for the Access Token
  225.       System.out.println("Trading the Request Token for an Access Token...");
  226.       try {
  227.         Token token = service.getAccessToken(requestToken, verifier);
  228.         System.out.println(token); //Use this output to copy the token into your code so you don't have to do this over and over.
  229.         return token;
  230.       } catch (OAuthException ex) {
  231.         int choice = JOptionPane.showConfirmDialog(null, "There was an OAuthException" + newline
  232.                 + ex + newline
  233.                 + "Would you like to try again?", "OAuthException", JOptionPane.YES_NO_OPTION);
  234.         if (choice == JOptionPane.NO_OPTION) {
  235.           break;
  236.         }
  237.       }
  238.     } while (true);
  239.     return null;
  240.   }
  241.  
  242.   /**
  243.    * Sets the video's meta-data
  244.    */
  245.   private static void setVimeoVideoInfo(Response response, OAuthService service, Token token, String vimeoAPIURL) {
  246.     OAuthRequest request;
  247.     Document doc = readXML(response.getBody());
  248.     org.w3c.dom.Element ticketElement = (org.w3c.dom.Element) doc.getDocumentElement().getElementsByTagName("ticket").item(0);
  249.     String vimeoVideoId = ticketElement.getAttribute("video_id");
  250.     //Set title, description, category, tags, private
  251.     //Set Title
  252.     request = new OAuthRequest(Verb.POST, vimeoAPIURL);
  253.     request.addQuerystringParameter("method", "vimeo.videos.setTitle");
  254.     request.addQuerystringParameter("title", "Test Title");
  255.     request.addQuerystringParameter("video_id", vimeoVideoId);
  256.     signAndSendToVimeo(request, "setTitle", true);
  257.  
  258.     //Set description
  259.     request = new OAuthRequest(Verb.POST, vimeoAPIURL);
  260.     request.addQuerystringParameter("method", "vimeo.videos.setDescription");
  261.     request.addQuerystringParameter("description", "This is my test description");
  262.     request.addQuerystringParameter("video_id", vimeoVideoId);
  263.     signAndSendToVimeo(request, "setDescription", true);
  264.  
  265.     List<String> videoTags = new ArrayList<String>();
  266.     videoTags.add("test1");
  267.     videoTags.add("");
  268.     videoTags.add("test3");
  269.     videoTags.add("test4");
  270.     videoTags.add("test 5");
  271.     videoTags.add("test-6");
  272.     videoTags.add("test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7");
  273.  
  274.     //Create tags string
  275.     String tags = "";
  276.     for (String tag : videoTags) {
  277.       tags += tag + ", ";
  278.     }
  279.     tags.replace(", , ", ", "); //if by chance there are empty tags.
  280.  
  281.     //Set Tags
  282.     request = new OAuthRequest(Verb.POST, vimeoAPIURL);
  283.     request.addQuerystringParameter("method", "vimeo.videos.addTags");
  284.     request.addQuerystringParameter("tags", tags);
  285.     request.addQuerystringParameter("video_id", vimeoVideoId);
  286.     signAndSendToVimeo(request, "addTags", true);
  287.  
  288.     //Set Privacy
  289.     request = new OAuthRequest(Verb.POST, vimeoAPIURL);
  290.     request.addQuerystringParameter("method", "vimeo.videos.setPrivacy");
  291.     request.addQuerystringParameter("privacy", (true) ? "nobody" : "anybody");
  292.     request.addQuerystringParameter("video_id", vimeoVideoId);
  293.     signAndSendToVimeo(request, "setPrivacy", true);
  294.   }
  295.  
  296.   /**
  297.   * Signs the request and sends it. Returns the response.
  298.   *
  299.   * @param request
  300.   * @return response
  301.   */
  302.   public static Response signAndSendToVimeo(OAuthRequest request, String description, boolean printBody) throws org.scribe.exceptions.OAuthException {
  303.     System.out.println(newline + newline
  304.             + "Signing " + description + " request:"
  305.             + ((printBody && !request.getBodyContents().isEmpty()) ? newline + "\tBody Contents:" + request.getBodyContents() : "")
  306.             + ((!request.getHeaders().isEmpty()) ? newline + "\tHeaders: " + request.getHeaders() : ""));
  307.     service.signRequest(accessToken, request);
  308.     printRequest(request, description);
  309.     Response response = request.send();
  310.     printResponse(response, description, printBody);
  311.     return response;
  312.   }
  313.  
  314.   /**
  315.    * Prints the given description, and the headers, verb, and complete URL of the request.
  316.    *
  317.    * @param request
  318.    * @param description
  319.    */
  320.   private static void printRequest(OAuthRequest request, String description) {
  321.     System.out.println();
  322.     System.out.println(description + " >>> Request");
  323.     System.out.println("Headers: " + request.getHeaders());
  324.     System.out.println("Verb: " + request.getVerb());
  325.     System.out.println("Complete URL: " + request.getCompleteUrl());
  326.   }
  327.  
  328.   /**
  329.    * Prints the given description, and the code, headers, and body of the given response
  330.    *
  331.    * @param response
  332.    * @param description
  333.    */
  334.   private static void printResponse(Response response, String description, boolean printBody) {
  335.     System.out.println();
  336.     System.out.println(description + " >>> Response");
  337.     System.out.println("Code: " + response.getCode());
  338.     System.out.println("Headers: " + response.getHeaders());
  339.     if (printBody) {
  340.       System.out.println("Body: " + response.getBody());
  341.     }
  342.   }
  343.  
  344.   /**
  345.    * This method will Read the XML and act accordingly
  346.    *
  347.    * @param xmlString - the XML String
  348.    * @return the list of elements within the XML
  349.    */
  350.   private static Document readXML(String xmlString) {
  351.     Document doc = null;
  352.     try {
  353.       DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  354.       DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  355.       InputSource xmlStream = new InputSource();
  356.       xmlStream.setCharacterStream(new StringReader(xmlString));
  357.       doc = dBuilder.parse(xmlStream);
  358.     } catch (Exception e) {
  359.       e.printStackTrace();
  360.     }
  361.     return doc;
  362.   }
  363. }
Add Comment
Please, Sign In to add comment