Search in sources :

Example 21 with Credential

use of com.google.api.client.auth.oauth2.Credential in project api-samples by youtube.

the class AddSubscription method main.

/**
     * Subscribe the user's YouTube account to a user-selected channel.
     *
     * @param args command line args (not used).
     */
public static void main(String[] args) {
    // This OAuth 2.0 access scope allows for full read/write access to the
    // authenticated user's account.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");
    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "addsubscription");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-addsubscription-sample").build();
        // We get the user selected channel to subscribe.
        // Retrieve the channel ID that the user is subscribing to.
        String channelId = getChannelId();
        System.out.println("You chose " + channelId + " to subscribe.");
        // Create a resourceId that identifies the channel ID.
        ResourceId resourceId = new ResourceId();
        resourceId.setChannelId(channelId);
        resourceId.setKind("youtube#channel");
        // Create a snippet that contains the resourceId.
        SubscriptionSnippet snippet = new SubscriptionSnippet();
        snippet.setResourceId(resourceId);
        // Create a request to add the subscription and send the request.
        // The request identifies subscription metadata to insert as well
        // as information that the API server should return in its response.
        Subscription subscription = new Subscription();
        subscription.setSnippet(snippet);
        YouTube.Subscriptions.Insert subscriptionInsert = youtube.subscriptions().insert("snippet,contentDetails", subscription);
        Subscription returnedSubscription = subscriptionInsert.execute();
        // Print information from the API response.
        System.out.println("\n================== Returned Subscription ==================\n");
        System.out.println("  - Id: " + returnedSubscription.getId());
        System.out.println("  - Title: " + returnedSubscription.getSnippet().getTitle());
    } catch (GoogleJsonResponseException e) {
        System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) IOException(java.io.IOException) YouTube(com.google.api.services.youtube.YouTube) SubscriptionSnippet(com.google.api.services.youtube.model.SubscriptionSnippet) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) ResourceId(com.google.api.services.youtube.model.ResourceId) Subscription(com.google.api.services.youtube.model.Subscription)

Example 22 with Credential

use of com.google.api.client.auth.oauth2.Credential in project api-samples by youtube.

the class Captions method main.

/**
     * Upload, list, update, download, and delete caption tracks.
     *
     * @param args command line args (not used).
     */
public static void main(String[] args) {
    // This OAuth 2.0 access scope allows for full read/write access to the
    // authenticated user's account and requires requests to use an SSL connection.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.force-ssl");
    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "captions");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-captions-sample").build();
        // Prompt the user to specify the action of the be achieved.
        String actionString = getActionFromUser();
        System.out.println("You chose " + actionString + ".");
        Action action = Action.valueOf(actionString.toUpperCase());
        switch(action) {
            case UPLOAD:
                uploadCaption(getVideoId(), getLanguage(), getName(), getCaptionFromUser());
                break;
            case LIST:
                listCaptions(getVideoId());
                break;
            case UPDATE:
                updateCaption(getCaptionIDFromUser(), getUpdateCaptionFromUser());
                break;
            case DOWNLOAD:
                downloadCaption(getCaptionIDFromUser());
                break;
            case DELETE:
                deleteCaption(getCaptionIDFromUser());
                break;
            default:
                // All the available methods are used in sequence just for the sake
                // of an example.
                //Prompt the user to specify a video to upload the caption track for and
                // a language, a name, a binary file for the caption track. Then upload the
                // caption track with the values that are selected by the user.
                String videoId = getVideoId();
                uploadCaption(videoId, getLanguage(), getName(), getCaptionFromUser());
                List<Caption> captions = listCaptions(videoId);
                if (captions.isEmpty()) {
                    System.out.println("Can't get video caption tracks.");
                } else {
                    // Retrieve the first uploaded caption track.
                    String firstCaptionId = captions.get(0).getId();
                    updateCaption(firstCaptionId, null);
                    downloadCaption(firstCaptionId);
                    deleteCaption(firstCaptionId);
                }
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Credential(com.google.api.client.auth.oauth2.Credential) IOException(java.io.IOException) YouTube(com.google.api.services.youtube.YouTube) Caption(com.google.api.services.youtube.model.Caption)

Example 23 with Credential

use of com.google.api.client.auth.oauth2.Credential in project api-samples by youtube.

the class InvideoProgramming method main.

/**
     * This code sample demonstrates different ways that the API can be used to
     * promote your channel content. It includes code for the following tasks:
     * <ol>
     * <li>Feature a video.</li>
     * <li>Feature a link to a social media channel.</li>
     * <li>Set a watermark for videos on your channel.</li>
     * </ol>
     *
     * @param args command line args (not used).
     */
public static void main(String[] args) {
    // This OAuth 2.0 access scope allows for full read/write access to the
    // authenticated user's account.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");
    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "invideoprogramming");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-invideoprogramming-sample").build();
        // Construct a request to retrieve the current user's channel ID.
        // In the API response, only include channel information needed for
        // this use case. The channel's uploads playlist identifies the
        // channel's most recently uploaded video.
        // See https://developers.google.com/youtube/v3/docs/channels/list
        ChannelListResponse channelListResponse = youtube.channels().list("id,contentDetails").setMine(true).setFields("items(contentDetails/relatedPlaylists/uploads,id)").execute();
        // The user's default channel is the first item in the list. If the
        // user does not have a channel, this code should throw a
        // GoogleJsonResponseException explaining the issue.
        Channel myChannel = channelListResponse.getItems().get(0);
        String channelId = myChannel.getId();
        // The promotion appears 15000ms (15 seconds) before the video ends.
        InvideoTiming invideoTiming = new InvideoTiming();
        invideoTiming.setOffsetMs(BigInteger.valueOf(15000l));
        invideoTiming.setType("offsetFromEnd");
        // This is one type of promotion and promotes a video.
        PromotedItemId promotedItemId = new PromotedItemId();
        promotedItemId.setType("video");
        promotedItemId.setVideoId(FEATURED_VIDEO_ID);
        // Set a custom message providing additional information about the
        // promoted video or your channel.
        PromotedItem promotedItem = new PromotedItem();
        promotedItem.setCustomMessage("Check out this video about WebM!");
        promotedItem.setId(promotedItemId);
        // Construct an object representing the invideo promotion data, and
        // add it to the channel.
        InvideoPromotion invideoPromotion = new InvideoPromotion();
        invideoPromotion.setDefaultTiming(invideoTiming);
        invideoPromotion.setItems(Lists.newArrayList(promotedItem));
        Channel channel = new Channel();
        channel.setId(channelId);
        channel.setInvideoPromotion(invideoPromotion);
        Channel updateChannelResponse = youtube.channels().update("invideoPromotion", channel).execute();
        // Print data from the API response.
        System.out.println("\n================== Updated Channel Information ==================\n");
        System.out.println("\t- Channel ID: " + updateChannelResponse.getId());
        InvideoPromotion promotions = updateChannelResponse.getInvideoPromotion();
        // We only care about the first item
        promotedItem = promotions.getItems().get(0);
        System.out.println("\t- Invideo promotion video ID: " + promotedItem.getId().getVideoId());
        System.out.println("\t- Promotion message: " + promotedItem.getCustomMessage());
        // In-video programming can also be used to feature links to
        // associated websites, merchant sites, or social networking sites.
        // The code below overrides the promotional video set above by
        // featuring a link to the YouTube Developers Twitter feed.
        PromotedItemId promotedTwitterFeed = new PromotedItemId();
        promotedTwitterFeed.setType("website");
        promotedTwitterFeed.setWebsiteUrl("https://twitter.com/youtubedev");
        promotedItem = new PromotedItem();
        promotedItem.setCustomMessage("Follow us on Twitter!");
        promotedItem.setId(promotedTwitterFeed);
        invideoPromotion.setItems(Lists.newArrayList(promotedItem));
        channel.setInvideoPromotion(invideoPromotion);
        // Call the API to set the in-video promotion data.
        updateChannelResponse = youtube.channels().update("invideoPromotion", channel).execute();
        // Print data from the API response.
        System.out.println("\n================== Updated Channel Information ==================\n");
        System.out.println("\t- Channel ID: " + updateChannelResponse.getId());
        promotions = updateChannelResponse.getInvideoPromotion();
        promotedItem = promotions.getItems().get(0);
        System.out.println("\t- Invideo promotion URL: " + promotedItem.getId().getWebsiteUrl());
        System.out.println("\t- Promotion message: " + promotedItem.getCustomMessage());
        // This example sets a custom watermark for the channel. The image
        // used is the watermark.jpg file in the "resources/" directory.
        InputStreamContent mediaContent = new InputStreamContent("image/jpeg", InvideoProgramming.class.getResourceAsStream("/watermark.jpg"));
        // Indicate that the watermark should display during the last 15
        // seconds of the video.
        InvideoTiming watermarkTiming = new InvideoTiming();
        watermarkTiming.setType("offsetFromEnd");
        watermarkTiming.setDurationMs(BigInteger.valueOf(15000l));
        watermarkTiming.setOffsetMs(BigInteger.valueOf(15000l));
        InvideoBranding invideoBranding = new InvideoBranding();
        invideoBranding.setTiming(watermarkTiming);
        youtube.watermarks().set(channelId, invideoBranding, mediaContent).execute();
    } catch (GoogleJsonResponseException e) {
        System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) IOException(java.io.IOException) YouTube(com.google.api.services.youtube.YouTube) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) InputStreamContent(com.google.api.client.http.InputStreamContent)

Example 24 with Credential

use of com.google.api.client.auth.oauth2.Credential in project api-samples by youtube.

the class MyUploads method main.

/**
     * Authorize the user, call the youtube.channels.list method to retrieve
     * the playlist ID for the list of videos uploaded to the user's channel,
     * and then call the youtube.playlistItems.list method to retrieve the
     * list of videos in that playlist.
     *
     * @param args command line args (not used).
     */
public static void main(String[] args) {
    // This OAuth 2.0 access scope allows for read-only access to the
    // authenticated user's account, but not other types of account access.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.readonly");
    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "myuploads");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-myuploads-sample").build();
        // Call the API's channels.list method to retrieve the
        // resource that represents the authenticated user's channel.
        // In the API response, only include channel information needed for
        // this use case. The channel's contentDetails part contains
        // playlist IDs relevant to the channel, including the ID for the
        // list that contains videos uploaded to the channel.
        YouTube.Channels.List channelRequest = youtube.channels().list("contentDetails");
        channelRequest.setMine(true);
        channelRequest.setFields("items/contentDetails,nextPageToken,pageInfo");
        ChannelListResponse channelResult = channelRequest.execute();
        List<Channel> channelsList = channelResult.getItems();
        if (channelsList != null) {
            // The user's default channel is the first item in the list.
            // Extract the playlist ID for the channel's videos from the
            // API response.
            String uploadPlaylistId = channelsList.get(0).getContentDetails().getRelatedPlaylists().getUploads();
            // Define a list to store items in the list of uploaded videos.
            List<PlaylistItem> playlistItemList = new ArrayList<PlaylistItem>();
            // Retrieve the playlist of the channel's uploaded videos.
            YouTube.PlaylistItems.List playlistItemRequest = youtube.playlistItems().list("id,contentDetails,snippet");
            playlistItemRequest.setPlaylistId(uploadPlaylistId);
            // Only retrieve data used in this application, thereby making
            // the application more efficient. See:
            // https://developers.google.com/youtube/v3/getting-started#partial
            playlistItemRequest.setFields("items(contentDetails/videoId,snippet/title,snippet/publishedAt),nextPageToken,pageInfo");
            String nextToken = "";
            // there are still more items to retrieve.
            do {
                playlistItemRequest.setPageToken(nextToken);
                PlaylistItemListResponse playlistItemResult = playlistItemRequest.execute();
                playlistItemList.addAll(playlistItemResult.getItems());
                nextToken = playlistItemResult.getNextPageToken();
            } while (nextToken != null);
            // Prints information about the results.
            prettyPrint(playlistItemList.size(), playlistItemList.iterator());
        }
    } catch (GoogleJsonResponseException e) {
        e.printStackTrace();
        System.err.println("There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) Channel(com.google.api.services.youtube.model.Channel) ArrayList(java.util.ArrayList) YouTube(com.google.api.services.youtube.YouTube) PlaylistItemListResponse(com.google.api.services.youtube.model.PlaylistItemListResponse) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) ChannelListResponse(com.google.api.services.youtube.model.ChannelListResponse) PlaylistItem(com.google.api.services.youtube.model.PlaylistItem)

Example 25 with Credential

use of com.google.api.client.auth.oauth2.Credential in project api-samples by youtube.

the class PlaylistLocalizations method main.

/**
     * Set and retrieve localized metadata for a playlist.
     *
     * @param args command line args (not used).
     */
public static void main(String[] args) {
    // This OAuth 2.0 access scope allows for full read/write access to the
    // authenticated user's account.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");
    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "localizations");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-localizations-sample").build();
        // Prompt the user to specify the action of the be achieved.
        String actionString = getActionFromUser();
        System.out.println("You chose " + actionString + ".");
        //Map the user input to the enum values.
        Action action = Action.valueOf(actionString.toUpperCase());
        switch(action) {
            case SET:
                setPlaylistLocalization(getId("playlist"), getDefaultLanguage(), getLanguage(), getMetadata("title"), getMetadata("description"));
                break;
            case GET:
                getPlaylistLocalization(getId("playlist"), getLanguage());
                break;
            case LIST:
                listPlaylistLocalizations(getId("playlist"));
                break;
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Credential(com.google.api.client.auth.oauth2.Credential) IOException(java.io.IOException) YouTube(com.google.api.services.youtube.YouTube)

Aggregations

Credential (com.google.api.client.auth.oauth2.Credential)33 IOException (java.io.IOException)24 GoogleJsonResponseException (com.google.api.client.googleapis.json.GoogleJsonResponseException)21 YouTube (com.google.api.services.youtube.YouTube)20 StoredCredential (com.google.api.client.auth.oauth2.StoredCredential)5 InputStreamContent (com.google.api.client.http.InputStreamContent)4 AuthorizationCodeInstalledApp (com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp)3 LocalServerReceiver (com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver)3 GoogleAuthorizationCodeFlow (com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow)3 GoogleClientSecrets (com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets)3 MediaHttpUploader (com.google.api.client.googleapis.media.MediaHttpUploader)3 MediaHttpUploaderProgressListener (com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener)3 FileDataStoreFactory (com.google.api.client.util.store.FileDataStoreFactory)3 ArrayList (java.util.ArrayList)3 Calendar (java.util.Calendar)3 GoogleCredential (com.google.api.client.googleapis.auth.oauth2.GoogleCredential)2 HttpRequest (com.google.api.client.http.HttpRequest)2 DateTime (com.google.api.client.util.DateTime)2 Channel (com.google.api.services.youtube.model.Channel)2 ChannelListResponse (com.google.api.services.youtube.model.ChannelListResponse)2