Search in sources :

Example 1 with SearchResult

use of com.google.api.services.youtube.model.SearchResult in project SkyBot by duncte123.

the class SpotifyAudioSourceManager method loadItem.

@Override
public AudioItem loadItem(DefaultAudioPlayerManager manager, AudioReference reference) {
    if (isSpotifyAlbum(reference.identifier)) {
        if (youtube == null)
            return null;
        Matcher res = SPOTIFY_ALBUM_REGEX.matcher(reference.identifier);
        if (res.matches()) {
            try {
                final List<AudioTrack> playList = new ArrayList<>();
                final Album album = api.getAlbum(res.group(res.groupCount())).build().get();
                for (SimpleTrack t : album.getTracks().getItems()) {
                    List<SearchResult> results = searchYoutube(album.getArtists().get(0).getName() + " - " + t.getName());
                    playList.addAll(doThingWithPlaylist(results));
                }
                return new BasicAudioPlaylist(album.getName(), playList, playList.get(0), false);
            } catch (Exception e) {
                // logger.error("Something went wrong!", e);
                throw new FriendlyException(e.getMessage(), FriendlyException.Severity.FAULT, e);
            // return null;
            }
        }
    } else if (isSpotifyPlaylist(reference.identifier)) {
        if (youtube == null)
            return null;
        Matcher res = SPOTIFY_PLAYLIST_REGEX.matcher(reference.identifier);
        if (res.matches()) {
            try {
                final List<AudioTrack> finalPlaylist = new ArrayList<>();
                final Playlist spotifyPlaylist = api.getPlaylist(res.group(res.groupCount() - 1), res.group(res.groupCount())).build().get();
                for (PlaylistTrack playlistTrack : spotifyPlaylist.getTracks().getItems()) {
                    List<SearchResult> results = searchYoutube(playlistTrack.getTrack().getArtists().get(0).getName() + " - " + playlistTrack.getTrack().getName());
                    finalPlaylist.addAll(doThingWithPlaylist(results));
                }
                return new BasicAudioPlaylist(spotifyPlaylist.getName(), finalPlaylist, finalPlaylist.get(0), false);
            } catch (Exception e) {
                // logger.error("Something went wrong!", e);
                throw new FriendlyException(e.getMessage(), FriendlyException.Severity.FAULT, e);
            // return null;
            }
        }
    } else if (isSpotyfyTrack(reference.identifier)) {
        if (youtube == null)
            return null;
        Matcher res = SPOTIFY_TRACK_REGEX.matcher(reference.identifier);
        if (res.matches()) {
            try {
                final Track track = api.getTrack(res.group(res.groupCount())).build().get();
                List<SearchResult> results = searchYoutube(track.getArtists().get(0).getName() + " - " + track.getName());
                Video v = getVideoById(results.get(0).getId().getVideoId());
                return new SpotifyAudioTrack(new AudioTrackInfo(v.getSnippet().getTitle(), v.getSnippet().getChannelId(), toLongDuration(v.getContentDetails().getDuration()), v.getId(), false, "https://youtube.com/watch?v=" + v.getId()), youtubeAudioSourceManager);
            // return youtubeSearchProvider.loadSearchResult(track.getArtists().get(0).getName() + " - "+ track.getName());
            } catch (Exception e) {
                // logger.error("Something went wrong!", e);
                throw new FriendlyException(e.getMessage(), FriendlyException.Severity.FAULT, e);
            // return null;
            }
        }
    }
    /*if(isSpotifyAlbum(reference.identifier)) {
            if(this.youtubeAudioSourceManager == null)
                return null;
            Matcher res = SPOTIFY_ALBUM_REGEX.matcher(reference.identifier);
            if (res.matches()) {

                try {
                    final List<AudioTrack> playList = new ArrayList<>();
                    final Album album = api.getAlbum(res.group(res.groupCount())).build().get();
                    for(SimpleTrack t : album.getTracks().getItems()){
                        String fakeUrl = album.getArtists().get(0).getName() + " - "+ t.getName();
                        List<AudioTrack> tracks = ((AudioPlaylist)youtubeSearchProvider.loadSearchResult(fakeUrl)).getTracks();
                        if(tracks.size() > 0)
                            playList.add(tracks.get(0));
                    }
                    return new BasicAudioPlaylist(album.getName(), playList, playList.get(0), false);
                } catch (Exception e) {
                    //logger.error("Something went wrong!", e);
                    throw new FriendlyException(e.getMessage(), FriendlyException.Severity.FAULT, e);
                    //return null;
                }
            }
        } else if(isSpotifyPlaylist(reference.identifier)) {
            if(this.youtubeAudioSourceManager == null)
                return null;
            Matcher res = SPOTIFY_PLAYLIST_REGEX.matcher(reference.identifier);
            if (res.matches()) {

                try {
                    final List<AudioTrack> finalPlaylist = new ArrayList<>();
                    final Playlist spotifyPlaylist = api.getPlaylist(res.group(res.groupCount()-1), res.group(res.groupCount())).build().get();
                    for(PlaylistTrack playlistTrack : spotifyPlaylist.getTracks().getItems()){
                        String fakeUrl = playlistTrack.getTrack().getArtists().get(0).getName() + " - " + playlistTrack.getTrack().getName();
                        System.out.println(fakeUrl);
                        List<AudioTrack> tracks = ((AudioPlaylist)youtubeSearchProvider.loadSearchResult(fakeUrl)).getTracks();
                        if(tracks.size() > 0)
                            finalPlaylist.add(tracks.get(0));
                    }
                    return new BasicAudioPlaylist(spotifyPlaylist.getName(), finalPlaylist, finalPlaylist.get(0), false);
                } catch (Exception e) {
                    //logger.error("Something went wrong!", e);
                    throw new FriendlyException(e.getMessage(), FriendlyException.Severity.FAULT, e);
                    //return null;
                }
            }
        } else if(isSpotyfyTrack(reference.identifier)) {
            if(this.youtubeAudioSourceManager == null)
                return null;
            Matcher res = SPOTIFY_TRACK_REGEX.matcher(reference.identifier);
            if (res.matches()) {

                try {
                    final Track track = api.getTrack(res.group(res.groupCount())).build().get();
                    return youtubeSearchProvider.loadSearchResult(track.getArtists().get(0).getName() + " - "+ track.getName());
                } catch (Exception e) {
                    //logger.error("Something went wrong!", e);
                    throw new FriendlyException(e.getMessage(), FriendlyException.Severity.FAULT, e);
                    //return null;
                }
            }
        }*/
    return null;
}
Also used : Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) SearchResult(com.google.api.services.youtube.model.SearchResult) GeneralSecurityException(java.security.GeneralSecurityException) FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException) IOException(java.io.IOException) FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException) Video(com.google.api.services.youtube.model.Video) ArrayList(java.util.ArrayList) List(java.util.List)

Example 2 with SearchResult

use of com.google.api.services.youtube.model.SearchResult 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 3 with SearchResult

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

the class Search method prettyPrint.

/*
     * Prints out all results in the Iterator. For each result, print the
     * title, video ID, and thumbnail.
     *
     * @param iteratorSearchResults Iterator of SearchResults to print
     *
     * @param query Search query (String)
     */
private static void prettyPrint(Iterator<SearchResult> iteratorSearchResults, String query) {
    System.out.println("\n=============================================================");
    System.out.println("   First " + NUMBER_OF_VIDEOS_RETURNED + " videos for search on \"" + query + "\".");
    System.out.println("=============================================================\n");
    if (!iteratorSearchResults.hasNext()) {
        System.out.println(" There aren't any results for your query.");
    }
    while (iteratorSearchResults.hasNext()) {
        SearchResult singleVideo = iteratorSearchResults.next();
        ResourceId rId = singleVideo.getId();
        // item will not contain a video ID.
        if (rId.getKind().equals("youtube#video")) {
            Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().getDefault();
            System.out.println(" Video Id" + rId.getVideoId());
            System.out.println(" Title: " + singleVideo.getSnippet().getTitle());
            System.out.println(" Thumbnail: " + thumbnail.getUrl());
            System.out.println("\n-------------------------------------------------------------\n");
        }
    }
}
Also used : ResourceId(com.google.api.services.youtube.model.ResourceId) SearchResult(com.google.api.services.youtube.model.SearchResult) Thumbnail(com.google.api.services.youtube.model.Thumbnail)

Example 4 with SearchResult

use of com.google.api.services.youtube.model.SearchResult in project SkyBot by duncte123.

the class SpotifyAudioSourceManager method doThingWithPlaylist.

private List<AudioTrack> doThingWithPlaylist(List<SearchResult> results) throws Exception {
    List<AudioTrack> playList = new ArrayList<>();
    if (results.size() > 0) {
        SearchResult video = results.get(0);
        ResourceId rId = video.getId();
        if (rId.getKind().equals("youtube#video")) {
            Video v = getVideoById(video.getId().getVideoId());
            playList.add(new SpotifyAudioTrack(new AudioTrackInfo(v.getSnippet().getTitle(), v.getSnippet().getChannelId(), toLongDuration(v.getContentDetails().getDuration()), video.getId().getVideoId(), false, "https://youtube.com/watch?v=" + video.getId().getVideoId()), youtubeAudioSourceManager));
        }
    }
    return playList;
}
Also used : ResourceId(com.google.api.services.youtube.model.ResourceId) Video(com.google.api.services.youtube.model.Video) ArrayList(java.util.ArrayList) SearchResult(com.google.api.services.youtube.model.SearchResult)

Example 5 with SearchResult

use of com.google.api.services.youtube.model.SearchResult in project opencast by opencast.

the class YouTubeV3PublicationServiceImpl method retract.

private void retract(final String seriesTitle, final String episodeName) throws Exception {
    final List<SearchResult> items = youTubeService.searchMyVideos(truncateTitleToMaxFieldLength(episodeName, false), null, 1).getItems();
    if (!items.isEmpty()) {
        final String videoId = items.get(0).getId().getVideoId();
        if (seriesTitle != null) {
            final Playlist playlist = youTubeService.getMyPlaylistByTitle(truncateTitleToMaxFieldLength(seriesTitle, true));
            youTubeService.removeVideoFromPlaylist(playlist.getId(), videoId);
        }
        youTubeService.removeMyVideo(videoId);
    }
}
Also used : Playlist(com.google.api.services.youtube.model.Playlist) SearchResult(com.google.api.services.youtube.model.SearchResult)

Aggregations

SearchResult (com.google.api.services.youtube.model.SearchResult)6 Video (com.google.api.services.youtube.model.Video)3 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 GoogleJsonResponseException (com.google.api.client.googleapis.json.GoogleJsonResponseException)2 HttpRequest (com.google.api.client.http.HttpRequest)2 HttpRequestInitializer (com.google.api.client.http.HttpRequestInitializer)2 YouTube (com.google.api.services.youtube.YouTube)2 ResourceId (com.google.api.services.youtube.model.ResourceId)2 SearchListResponse (com.google.api.services.youtube.model.SearchListResponse)2 InputStream (java.io.InputStream)2 Properties (java.util.Properties)2 Joiner (com.google.api.client.util.Joiner)1 Playlist (com.google.api.services.youtube.model.Playlist)1 Thumbnail (com.google.api.services.youtube.model.Thumbnail)1 VideoListResponse (com.google.api.services.youtube.model.VideoListResponse)1 FriendlyException (com.sedmelluq.discord.lavaplayer.tools.FriendlyException)1 GeneralSecurityException (java.security.GeneralSecurityException)1 List (java.util.List)1 Matcher (java.util.regex.Matcher)1