Search in sources :

Example 6 with YouTube

use of com.google.api.services.youtube.YouTube in project api-samples by youtube.

the class GeolocationSearch method main.

/**
     * Initialize a YouTube object to search for videos on YouTube. Then
     * display the name and thumbnail image of each video in the result set.
     *
     * @param args command line args.
     */
public static void main(String[] args) {
    // Read the developer key from the properties file.
    Properties properties = new Properties();
    try {
        InputStream in = GeolocationSearch.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
        properties.load(in);
    } catch (IOException e) {
        System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() + " : " + e.getMessage());
        System.exit(1);
    }
    try {
        // This object is used to make YouTube Data API requests. The last
        // argument is required, but since we don't need anything
        // initialized when the HttpRequest is initialized, we override
        // the interface and provide a no-op function.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {

            @Override
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("youtube-cmdline-geolocationsearch-sample").build();
        // Prompt the user to enter a query term.
        String queryTerm = getInputQuery();
        // Prompt the user to enter location coordinates.
        String location = getInputLocation();
        // Prompt the user to enter a location radius.
        String locationRadius = getInputLocationRadius();
        // Define the API request for retrieving search results.
        YouTube.Search.List search = youtube.search().list("id,snippet");
        // Set your developer key from the {{ Google Cloud Console }} for
        // non-authenticated requests. See:
        // {{ https://cloud.google.com/console }}
        String apiKey = properties.getProperty("youtube.apikey");
        search.setKey(apiKey);
        search.setQ(queryTerm);
        search.setLocation(location);
        search.setLocationRadius(locationRadius);
        // Restrict the search results to only include videos. See:
        // https://developers.google.com/youtube/v3/docs/search/list#type
        search.setType("video");
        // As a best practice, only retrieve the fields that the
        // application uses.
        search.setFields("items(id/videoId)");
        search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
        // Call the API and print results.
        SearchListResponse searchResponse = search.execute();
        List<SearchResult> searchResultList = searchResponse.getItems();
        List<String> videoIds = new ArrayList<String>();
        if (searchResultList != null) {
            // Merge video IDs
            for (SearchResult searchResult : searchResultList) {
                videoIds.add(searchResult.getId().getVideoId());
            }
            Joiner stringJoiner = Joiner.on(',');
            String videoId = stringJoiner.join(videoIds);
            // Call the YouTube Data API's youtube.videos.list method to
            // retrieve the resources that represent the specified videos.
            YouTube.Videos.List listVideosRequest = youtube.videos().list("snippet, recordingDetails").setId(videoId);
            VideoListResponse listResponse = listVideosRequest.execute();
            List<Video> videoList = listResponse.getItems();
            if (videoList != null) {
                prettyPrint(videoList.iterator(), queryTerm);
            }
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println("There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
    } catch (IOException e) {
        System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) SearchListResponse(com.google.api.services.youtube.model.SearchListResponse) Joiner(com.google.api.client.util.Joiner) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) SearchResult(com.google.api.services.youtube.model.SearchResult) IOException(java.io.IOException) Properties(java.util.Properties) YouTube(com.google.api.services.youtube.YouTube) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Video(com.google.api.services.youtube.model.Video) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer) VideoListResponse(com.google.api.services.youtube.model.VideoListResponse)

Example 7 with YouTube

use of com.google.api.services.youtube.YouTube in project HearthStats.net-Uploader by HearthStats.

the class UploadVideo method main.

/**
     * Upload the user-selected video to the user's YouTube channel. The code
     * looks for the video in the application's project folder and uses OAuth
     * 2.0 to authorize the API request.
     *
     * @param args command line args (not used).
     */
public static void main(String[] args) {
    // This OAuth 2.0 access scope allows an application to upload files
    // to the authenticated user's YouTube channel, but doesn't allow
    // other types of access.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.upload");
    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "uploadvideo");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-uploadvideo-sample").build();
        System.out.println("Uploading: " + SAMPLE_VIDEO_FILENAME);
        // Add extra information to the video before uploading.
        Video videoObjectDefiningMetadata = new Video();
        // Set the video to be publicly visible. This is the default
        // setting. Other supporting settings are "unlisted" and "private."
        VideoStatus status = new VideoStatus();
        status.setPrivacyStatus("public");
        videoObjectDefiningMetadata.setStatus(status);
        // Most of the video's metadata is set on the VideoSnippet object.
        VideoSnippet snippet = new VideoSnippet();
        // This code uses a Calendar instance to create a unique name and
        // description for test purposes so that you can easily upload
        // multiple files. You should remove this code from your project
        // and use your own standard names instead.
        Calendar cal = Calendar.getInstance();
        snippet.setTitle("Test Upload via Java on " + cal.getTime());
        snippet.setDescription("Video uploaded via YouTube Data API V3 using the Java library " + "on " + cal.getTime());
        // Set the keyword tags that you want to associate with the video.
        List<String> tags = new ArrayList<String>();
        tags.add("test");
        tags.add("example");
        tags.add("java");
        tags.add("YouTube Data API V3");
        tags.add("erase me");
        snippet.setTags(tags);
        // Add the completed snippet object to the video resource.
        videoObjectDefiningMetadata.setSnippet(snippet);
        InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT, UploadVideo.class.getResourceAsStream("/sample-video.mp4"));
        // Insert the video. The command sends three arguments. The first
        // specifies which information the API request is setting and which
        // information the API response should return. The second argument
        // is the video resource that contains metadata about the new video.
        // The third argument is the actual video content.
        YouTube.Videos.Insert videoInsert = youtube.videos().insert("snippet,statistics,status", videoObjectDefiningMetadata, mediaContent);
        // Set the upload type and add an event listener.
        MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();
        // Indicate whether direct media upload is enabled. A value of
        // "True" indicates that direct media upload is enabled and that
        // the entire media content will be uploaded in a single request.
        // A value of "False," which is the default, indicates that the
        // request will use the resumable media upload protocol, which
        // supports the ability to resume an upload operation after a
        // network interruption or other transmission failure, saving
        // time and bandwidth in the event of network failures.
        uploader.setDirectUploadEnabled(false);
        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {

            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch(uploader.getUploadState()) {
                    case INITIATION_STARTED:
                        System.out.println("Initiation Started");
                        break;
                    case INITIATION_COMPLETE:
                        System.out.println("Initiation Completed");
                        break;
                    case MEDIA_IN_PROGRESS:
                        System.out.println("Upload in progress");
                        System.out.println("Upload percentage: " + uploader.getProgress());
                        break;
                    case MEDIA_COMPLETE:
                        System.out.println("Upload Completed!");
                        break;
                    case NOT_STARTED:
                        System.out.println("Upload Not Started!");
                        break;
                }
            }
        };
        uploader.setProgressListener(progressListener);
        // Call the API and upload the video.
        Video returnedVideo = videoInsert.execute();
        // Print data about the newly inserted video from the API response.
        System.out.println("\n================== Returned Video ==================\n");
        System.out.println("  - Id: " + returnedVideo.getId());
        System.out.println("  - Title: " + returnedVideo.getSnippet().getTitle());
        System.out.println("  - Tags: " + returnedVideo.getSnippet().getTags());
        System.out.println("  - Privacy Status: " + returnedVideo.getStatus().getPrivacyStatus());
        System.out.println("  - Video Count: " + returnedVideo.getStatistics().getViewCount());
    } 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 : VideoSnippet(com.google.api.services.youtube.model.VideoSnippet) Credential(com.google.api.client.auth.oauth2.Credential) MediaHttpUploader(com.google.api.client.googleapis.media.MediaHttpUploader) VideoStatus(com.google.api.services.youtube.model.VideoStatus) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) MediaHttpUploaderProgressListener(com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener) IOException(java.io.IOException) YouTube(com.google.api.services.youtube.YouTube) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Video(com.google.api.services.youtube.model.Video) InputStreamContent(com.google.api.client.http.InputStreamContent)

Example 8 with YouTube

use of com.google.api.services.youtube.YouTube in project api-samples by youtube.

the class CreateBroadcast method main.

/**
     * Create and insert a liveBroadcast resource.
     */
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, "createbroadcast");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-createbroadcast-sample").build();
        // Prompt the user to enter a title for the broadcast.
        String title = getBroadcastTitle();
        System.out.println("You chose " + title + " for broadcast title.");
        // Create a snippet with the title and scheduled start and end
        // times for the broadcast. Currently, those times are hard-coded.
        LiveBroadcastSnippet broadcastSnippet = new LiveBroadcastSnippet();
        broadcastSnippet.setTitle(title);
        broadcastSnippet.setScheduledStartTime(new DateTime("2024-01-30T00:00:00.000Z"));
        broadcastSnippet.setScheduledEndTime(new DateTime("2024-01-31T00:00:00.000Z"));
        // Set the broadcast's privacy status to "private". See:
        // https://developers.google.com/youtube/v3/live/docs/liveBroadcasts#status.privacyStatus
        LiveBroadcastStatus status = new LiveBroadcastStatus();
        status.setPrivacyStatus("private");
        LiveBroadcast broadcast = new LiveBroadcast();
        broadcast.setKind("youtube#liveBroadcast");
        broadcast.setSnippet(broadcastSnippet);
        broadcast.setStatus(status);
        // Construct and execute the API request to insert the broadcast.
        YouTube.LiveBroadcasts.Insert liveBroadcastInsert = youtube.liveBroadcasts().insert("snippet,status", broadcast);
        LiveBroadcast returnedBroadcast = liveBroadcastInsert.execute();
        // Print information from the API response.
        System.out.println("\n================== Returned Broadcast ==================\n");
        System.out.println("  - Id: " + returnedBroadcast.getId());
        System.out.println("  - Title: " + returnedBroadcast.getSnippet().getTitle());
        System.out.println("  - Description: " + returnedBroadcast.getSnippet().getDescription());
        System.out.println("  - Published At: " + returnedBroadcast.getSnippet().getPublishedAt());
        System.out.println("  - Scheduled Start Time: " + returnedBroadcast.getSnippet().getScheduledStartTime());
        System.out.println("  - Scheduled End Time: " + returnedBroadcast.getSnippet().getScheduledEndTime());
        // Prompt the user to enter a title for the video stream.
        title = getStreamTitle();
        System.out.println("You chose " + title + " for stream title.");
        // Create a snippet with the video stream's title.
        LiveStreamSnippet streamSnippet = new LiveStreamSnippet();
        streamSnippet.setTitle(title);
        // Define the content distribution network settings for the
        // video stream. The settings specify the stream's format and
        // ingestion type. See:
        // https://developers.google.com/youtube/v3/live/docs/liveStreams#cdn
        CdnSettings cdnSettings = new CdnSettings();
        cdnSettings.setFormat("1080p");
        cdnSettings.setIngestionType("rtmp");
        LiveStream stream = new LiveStream();
        stream.setKind("youtube#liveStream");
        stream.setSnippet(streamSnippet);
        stream.setCdn(cdnSettings);
        // Construct and execute the API request to insert the stream.
        YouTube.LiveStreams.Insert liveStreamInsert = youtube.liveStreams().insert("snippet,cdn", stream);
        LiveStream returnedStream = liveStreamInsert.execute();
        // Print information from the API response.
        System.out.println("\n================== Returned Stream ==================\n");
        System.out.println("  - Id: " + returnedStream.getId());
        System.out.println("  - Title: " + returnedStream.getSnippet().getTitle());
        System.out.println("  - Description: " + returnedStream.getSnippet().getDescription());
        System.out.println("  - Published At: " + returnedStream.getSnippet().getPublishedAt());
        // Construct and execute a request to bind the new broadcast
        // and stream.
        YouTube.LiveBroadcasts.Bind liveBroadcastBind = youtube.liveBroadcasts().bind(returnedBroadcast.getId(), "id,contentDetails");
        liveBroadcastBind.setStreamId(returnedStream.getId());
        returnedBroadcast = liveBroadcastBind.execute();
        // Print information from the API response.
        System.out.println("\n================== Returned Bound Broadcast ==================\n");
        System.out.println("  - Broadcast Id: " + returnedBroadcast.getId());
        System.out.println("  - Bound Stream Id: " + returnedBroadcast.getContentDetails().getBoundStreamId());
    } 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) DateTime(com.google.api.client.util.DateTime) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException)

Example 9 with YouTube

use of com.google.api.services.youtube.YouTube in project api-samples by youtube.

the class ListStreams method main.

/**
     * List streams for the user's channel.
     */
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, "liststreams");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-liststreams-sample").build();
        // Create a request to list liveStream resources.
        YouTube.LiveStreams.List livestreamRequest = youtube.liveStreams().list("id,snippet");
        // Modify results to only return the user's streams.
        livestreamRequest.setMine(true);
        // Execute the API request and return the list of streams.
        LiveStreamListResponse returnedListResponse = livestreamRequest.execute();
        List<LiveStream> returnedList = returnedListResponse.getItems();
        // Print information from the API response.
        System.out.println("\n================== Returned Streams ==================\n");
        for (LiveStream stream : returnedList) {
            System.out.println("  - Id: " + stream.getId());
            System.out.println("  - Title: " + stream.getSnippet().getTitle());
            System.out.println("  - Description: " + stream.getSnippet().getDescription());
            System.out.println("  - Published At: " + stream.getSnippet().getPublishedAt());
            System.out.println("\n-------------------------------------------------------------\n");
        }
    } 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) LiveStreamListResponse(com.google.api.services.youtube.model.LiveStreamListResponse) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) LiveStream(com.google.api.services.youtube.model.LiveStream)

Example 10 with YouTube

use of com.google.api.services.youtube.YouTube in project api-samples by youtube.

the class UploadThumbnail method main.

/**
     * Prompt the user to specify a video ID and the path for a thumbnail
     * image. Then call the API to set the image as the thumbnail for the video.
     *
     * @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, "uploadthumbnail");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-uploadthumbnail-sample").build();
        // Prompt the user to enter the video ID of the video being updated.
        String videoId = getVideoIdFromUser();
        System.out.println("You chose " + videoId + " to upload a thumbnail.");
        // Prompt the user to specify the location of the thumbnail image.
        File imageFile = getImageFromUser();
        System.out.println("You chose " + imageFile + " to upload.");
        // Create an object that contains the thumbnail image file's
        // contents.
        InputStreamContent mediaContent = new InputStreamContent(IMAGE_FILE_FORMAT, new BufferedInputStream(new FileInputStream(imageFile)));
        mediaContent.setLength(imageFile.length());
        // Create an API request that specifies that the mediaContent
        // object is the thumbnail of the specified video.
        Set thumbnailSet = youtube.thumbnails().set(videoId, mediaContent);
        // Set the upload type and add an event listener.
        MediaHttpUploader uploader = thumbnailSet.getMediaHttpUploader();
        // Indicate whether direct media upload is enabled. A value of
        // "True" indicates that direct media upload is enabled and that
        // the entire media content will be uploaded in a single request.
        // A value of "False," which is the default, indicates that the
        // request will use the resumable media upload protocol, which
        // supports the ability to resume an upload operation after a
        // network interruption or other transmission failure, saving
        // time and bandwidth in the event of network failures.
        uploader.setDirectUploadEnabled(false);
        // Set the upload state for the thumbnail image.
        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {

            @Override
            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch(uploader.getUploadState()) {
                    // sent.
                    case INITIATION_STARTED:
                        System.out.println("Initiation Started");
                        break;
                    //  completes.
                    case INITIATION_COMPLETE:
                        System.out.println("Initiation Completed");
                        break;
                    // uploaded.
                    case MEDIA_IN_PROGRESS:
                        System.out.println("Upload in progress");
                        System.out.println("Upload percentage: " + uploader.getProgress());
                        break;
                    //  been successfully uploaded.
                    case MEDIA_COMPLETE:
                        System.out.println("Upload Completed!");
                        break;
                    //  not started yet.
                    case NOT_STARTED:
                        System.out.println("Upload Not Started!");
                        break;
                }
            }
        };
        uploader.setProgressListener(progressListener);
        // Upload the image and set it as the specified video's thumbnail.
        ThumbnailSetResponse setResponse = thumbnailSet.execute();
        // Print the URL for the updated video's thumbnail image.
        System.out.println("\n================== Uploaded Thumbnail ==================\n");
        System.out.println("  - Url: " + setResponse.getItems().get(0).getDefault().getUrl());
    } 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) Set(com.google.api.services.youtube.YouTube.Thumbnails.Set) MediaHttpUploader(com.google.api.client.googleapis.media.MediaHttpUploader) MediaHttpUploaderProgressListener(com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener) ThumbnailSetResponse(com.google.api.services.youtube.model.ThumbnailSetResponse) YouTube(com.google.api.services.youtube.YouTube) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) InputStreamContent(com.google.api.client.http.InputStreamContent)

Aggregations

YouTube (com.google.api.services.youtube.YouTube)22 GoogleJsonResponseException (com.google.api.client.googleapis.json.GoogleJsonResponseException)21 Credential (com.google.api.client.auth.oauth2.Credential)20 IOException (java.io.IOException)19 InputStreamContent (com.google.api.client.http.InputStreamContent)4 Video (com.google.api.services.youtube.model.Video)4 ArrayList (java.util.ArrayList)4 MediaHttpUploader (com.google.api.client.googleapis.media.MediaHttpUploader)3 MediaHttpUploaderProgressListener (com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener)3 VideoSnippet (com.google.api.services.youtube.model.VideoSnippet)3 Calendar (java.util.Calendar)3 HttpRequest (com.google.api.client.http.HttpRequest)2 HttpRequestInitializer (com.google.api.client.http.HttpRequestInitializer)2 Channel (com.google.api.services.youtube.model.Channel)2 ChannelListResponse (com.google.api.services.youtube.model.ChannelListResponse)2 Comment (com.google.api.services.youtube.model.Comment)2 CommentSnippet (com.google.api.services.youtube.model.CommentSnippet)2 CommentThread (com.google.api.services.youtube.model.CommentThread)2 CommentThreadListResponse (com.google.api.services.youtube.model.CommentThreadListResponse)2 SearchListResponse (com.google.api.services.youtube.model.SearchListResponse)2