public void searchYoutube(View view) { String getURL = "https://gdata.youtube.com/feeds/api/videos?"; String searchTerm = new String(); EditText value = (EditText) MainActivity.reference.findViewById(R.id.editText1); String testURL = "https://www.youtube.com/results?search_query="; searchTerm = value.getText().toString(); searchTerm = searchTerm.replace(" ", "%20"); getURL = getURL + searchTerm; /* Intent intent = new Intent(Intent.ACTION_SEARCH); intent.setPackage("com.google.android.youtube"); intent.putExtra("query", testURL+searchTerm); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent);*/ final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); final AndroidJsonFactory JSON_FACTORY = new AndroidJsonFactory(); // AndroidJsonFactory jsonfactory = new AndroidJsonFactory(); YouTube youtube = new YouTube.Builder( HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() { public void initialize(HttpRequest request) throws IOException {} @Override public void initialize(com.google.api.client.http.HttpRequest arg0) throws IOException { // TODO Auto-generated method stub } }) .setApplicationName("IGiftSearchRsult") .build(); YouTube.Search.List search; try { search = youtube.search().list("id,snippet"); search.setKey(DEVELOPER_KEY); search.setQ("dogs"); search.setMaxResults((long) 25); System.out.println(search); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // SearchListResponse searchResponse = search. }
public Video getVideo() { if (this.video_id != null) { try { videoQuery = youtube.videos().list("id,snippet,statistics"); videoQuery.setKey(this.KEY); videoQuery.setId(this.video_id); } catch (IOException e) { Log.d("Videos.List", "Could not initialize Videos.List: " + e.getMessage()); } VideoListResponse response; try { response = videoQuery.execute(); } catch (IOException e) { Log.d("Videos.List", "Could not get video: " + e.getMessage()); return null; } List<Video> videos = response.getItems(); for (Video video : videos) { VideoStatistics stats = video.getStatistics(); if (stats != null) { return video; } } } return null; }
public ArrayList<YoutubeVideo> loadMore(String offset, String keyword, int max) { try { query = youtube.search().list("id,snippet"); query.setKey(this.KEY); query.setOrder("date"); query.setType("video"); query.setChannelId(this.channel_id); if (keyword != null) { query.setQ(keyword); } query.setPageToken(offset); query.setMaxResults((long) max); query.setFields(queryParams); } catch (IOException e) { Log.d("MORE", "Could not load more: " + e.getMessage()); } SearchListResponse response = null; try { response = query.execute(); } catch (GoogleJsonResponseException e) { switch (e.getStatusCode()) { case 403: this.KEY = this.context.getString(R.string.api_key2); query.setKey(this.KEY); try { response = query.execute(); } catch (IOException e1) { Log.d("MORE-KEY2", "Could not initialize: " + e1.getMessage()); } } } catch (IOException e) { Log.d("MORE", "Could not execute more: " + e.getMessage()); return null; } List<SearchResult> results = response.getItems(); ArrayList<YoutubeVideo> items = new ArrayList<YoutubeVideo>(); for (SearchResult result : results) { YoutubeVideo item = new YoutubeVideo(); item.setTitle(result.getSnippet().getTitle()); item.setDescription(result.getSnippet().getDescription()); item.setThumbnailURL(result.getSnippet().getThumbnails().getMedium().getUrl()); item.setId(result.getId().getVideoId()); item.setNextPageToken(response.getNextPageToken()); if (keyword != null) { item.setKeyword(keyword); } try { item.setDate(getDateFormat().parse(result.getSnippet().getPublishedAt().toString())); } catch (ParseException e) { e.printStackTrace(); } item.setChannel_id(this.channel_id); items.add(item); } return items; }
private void initChannel() { ChannelListResponse response = null; try { channelQuery = youtube.channels().list("id,snippet,brandingSettings,statistics"); channelQuery.setKey(this.KEY); channelQuery.setId(this.channel_id); channelQuery.setFields( "items(id,brandingSettings,snippet/title,snippet/description,snippet/thumbnails,statistics)"); } catch (IOException e) { Log.d("YC", "Could not init: " + e); } try { response = channelQuery.execute(); } catch (GoogleJsonResponseException e) { Log.d("YC", "Could not search: " + e.getMessage()); switch (e.getStatusCode()) { case 403: this.KEY = this.context.getString(R.string.api_key2); channelQuery.setKey(this.KEY); try { response = channelQuery.execute(); } catch (IOException e1) { Log.d("YC-KEY2", "Could not initialize: " + e1.getMessage()); } } } catch (IOException e) { e.printStackTrace(); } List<Channel> results = response.getItems(); for (Channel result : results) { channel.setChannel_id(this.channel_id); channel.setTitle(result.getSnippet().getTitle()); channel.setDescription(result.getSnippet().getDescription()); channel.setThumbnailURL(result.getSnippet().getThumbnails().getHigh().getUrl()); if (isTablet(this.context)) { channel.setBannerURL(result.getBrandingSettings().getImage().getBannerTabletImageUrl()); } else { channel.setBannerURL(result.getBrandingSettings().getImage().getBannerImageUrl()); } channel.setViewCount(result.getStatistics().getViewCount()); channel.setVideoCount(result.getStatistics().getVideoCount()); channel.setSubscriberCount(result.getStatistics().getSubscriberCount()); } }
public List<VideoItem> getFavoriteVideo(List<String> favoriteVideoIds) { Joiner stringJoiner = Joiner.on(','); String videoId = stringJoiner.join(favoriteVideoIds); // Log.d(TAG, "String video ID: " + videoId); // Call the YouTube Data API's youtube.videos.list method to // retrieve the resources that represent the specified videos YouTube.Videos.List listVideosRequest = null; try { listVideosRequest = youtube.videos().list("snippet, recordingDetails").setId(videoId); listVideosRequest.setKey(KEY2); VideoListResponse listResponse = listVideosRequest.execute(); List<Video> videoList = listResponse.getItems(); List<VideoItem> items = new ArrayList<VideoItem>(); for (Video video : videoList) { VideoItem item = new VideoItem(); item.setTitle(video.getSnippet().getTitle()); try { item.setPublishedDate( new SimpleDateFormat("MM/dd/yyyy") .format( (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .parse(video.getSnippet().getPublishedAt().toString())))); } catch (ParseException e) { Log.d(TAG, "Could parse the date: " + e); } item.setDescription(video.getSnippet().getDescription()); item.setThumbnailURL(video.getSnippet().getThumbnails().getDefault().getUrl()); // same as id in search method item.setId(video.getId()); // item.setViewCount(video.getStatistics().getViewCount().intValue()); // Log.d(TAG, "view count: " + // video.getStatistics().getViewCount().intValue()); items.add(item); } return items; } catch (IOException e) { Log.d(TAG, "Could not search: " + e); return null; } }
public YoutubeConnector(Context content) { youtube = new YouTube.Builder( new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() { @Override public void initialize(HttpRequest hr) throws IOException {} }) .setApplicationName(content.getString(R.string.app_name)) .build(); try { query = youtube.search().list("id,snippet"); query.setKey(KEY1); query.setType("video"); query.setFields( "items(id/videoId,snippet/title,snippet/publishedAt,snippet/description,snippet/thumbnails/default/url)"); query.setMaxResults(NUMBER_OF_VIDEOS_RETURNED); } catch (IOException e) { Log.d(TAG, "Could not initialize: " + e); } }
@SuppressWarnings("deprecation") @Override public Boolean crawl(RssEntityBean site) throws CrawlerException { log.info("start YouTube crawl channel id = " + site.url); Boolean updated = false; YouTube youtube = new YouTube.Builder( HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() { public void initialize(HttpRequest request) throws IOException {} }) .setApplicationName("youtube-cmdline-search-sample") .build(); try { YouTube.Search.List search = youtube.search().list("id,snippet"); String apiKey = Conf.getValue("youtube.appkey"); search.setKey(apiKey); search.setType("video"); search.setOrder("date"); search.setMaxResults(maxResult); search.setChannelId(site.url); SearchListResponse searchResponse = search.execute(); List<SearchResult> searchResultList = searchResponse.getItems(); log.info("search response video count = " + searchResultList.size()); for (SearchResult result : searchResultList) { SearchResultSnippet snippet = result.getSnippet(); DateTime publishDate = snippet.getPublishedAt(); DateTime lastCrawlDate = null; if (site.lastCrawl != null) { lastCrawlDate = new DateTime(site.lastCrawl); } if ((lastCrawlDate == null) || (publishDate.getValue() > lastCrawlDate.getValue())) { YouTube.Videos.List videolist = youtube.videos().list("id,snippet"); videolist.setId(result.getId().getVideoId()); videolist.setKey(apiKey); VideoListResponse videoListResponse = videolist.execute(); List<Video> videos = videoListResponse.getItems(); if (videos.size() != 1) { log.warn("video not found : " + videolist.getId()); continue; } Video video = videos.get(0); ArticleEntityBean article = new ArticleEntityBean(); article.link = video.getId(); article.title = snippet.getTitle(); article.description = snippet.getDescription(); article.imageUrl = snippet.getThumbnails().getDefault().getUrl(); article.url = site.url; article.createdAt = snippet.getPublishedAt(); String fixHour = Conf.getValue("fix_time"); Date now = new Date(); Date fixDate = new Date(now.getYear(), now.getMonth(), now.getDate(), Integer.parseInt(fixHour), 0); if (now.getTime() > fixDate.getTime()) { article.publishedAt = tomorrow; } else { article.publishedAt = today; } article.site = site.site; article.type = site.type; article.tags = site.defaultTag; log.info("save article video id = " + article.link + " / video title = " + article.title); article.save(); updated = true; } } } catch (IOException e) { log.warn("youtube api error : " + e.getMessage()); throw new CrawlerException(e); } log.info("end YouTube crawl"); return updated; }
/** * Initializes YouTube object to search for videos on YouTube (Youtube.Search.List). The program * then prints the names and thumbnails of each of the videos (only first 50 videos). */ public String videoIdFromQueryTerm(String queryTerm) { // Read the developer key from youtube.properties String videoId = null; Properties properties = new Properties(); // try { // InputStream in = Search.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 { /* * The YouTube object is used to make all API requests. The last argument is required, but * because 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( HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() { public void initialize(HttpRequest request) throws IOException {} }) .setApplicationName("youtube-cmdline-search-sample") .build(); // Get query term from user. // String queryTerm = getInputQuery(); YouTube.Search.List search = youtube.search().list("id,snippet"); /* * It is important to set your developer key from the Google Developer Console for * non-authenticated requests (found under the API Access tab at this link: * code.google.com/apis/). This is good practice and increased your quota. */ String apiKey = "AIzaSyB--WhmXYTrUlitFPWtiPZu8V1w_iPRCbw"; search.setKey(apiKey); search.setQ(queryTerm); /* * We are only searching for videos (not playlists or channels). If we were searching for * more, we would add them as a string like this: "video,playlist,channel". */ search.setType("video"); /* * This method reduces the info returned to only the fields we need and makes calls more * efficient. */ search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)"); search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED); SearchListResponse searchResponse = search.execute(); List<SearchResult> searchResultList = searchResponse.getItems(); SearchResult searchResult = searchResultList.get(0); ResourceId rId = searchResult.getId(); videoId = rId.getVideoId(); // if (searchResultList != null) { // prettyPrint(searchResultList.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(); } return videoId; }
/** * 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 = ""; // Call the API one or more times to retrieve all items in the // list. As long as the API response returns a nextPageToken, // 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(); } }