com.google.api.services.youtube.YouTube Java Examples

The following examples show how to use com.google.api.services.youtube.YouTube. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: YouTubeSingleton.java    From YouTube-In-Background with MIT License 6 votes vote down vote up
private YouTubeSingleton(Context context)
{
    String appName = context.getString(R.string.app_name);
    credential = GoogleAccountCredential
            .usingOAuth2(context, Arrays.asList(SCOPES))
            .setBackOff(new ExponentialBackOff());

    youTube = new YouTube.Builder(
            new NetHttpTransport(),
            new JacksonFactory(),
            httpRequest -> {}
    ).setApplicationName(appName).build();

    youTubeWithCredentials = new YouTube.Builder(
            new NetHttpTransport(),
            new JacksonFactory(),
            credential
    ).setApplicationName(appName).build();
}
 
Example #2
Source File: YoutubeProviderTest.java    From streams with Apache License 2.0 6 votes vote down vote up
private YoutubeProvider buildProvider(YoutubeConfiguration config) {
  return new YoutubeProvider(config) {

    @Override
    protected YouTube createYouTubeClient() throws IOException {
      return mock(YouTube.class);
    }

    @Override
    protected Runnable getDataCollector(BackOffStrategy strategy, BlockingQueue<StreamsDatum> queue, YouTube youtube, UserInfo userInfo) {
      final BlockingQueue<StreamsDatum> q = queue;
      return () -> {
        try {
          q.put(new StreamsDatum(null));
        } catch (InterruptedException ie) {
          fail("Test was interrupted");
        }
      };
    }
  };
}
 
Example #3
Source File: YoutubeProvider.java    From streams with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
protected YouTube createYouTubeClient() throws IOException, GeneralSecurityException {
  GoogleCredential.Builder credentialBuilder = new GoogleCredential.Builder()
      .setTransport(HTTP_TRANSPORT)
      .setJsonFactory(JSON_FACTORY)
      .setServiceAccountId(getConfig().getOauth().getServiceAccountEmailAddress())
      .setServiceAccountScopes(scopes);

  if (StringUtils.isNotEmpty(getConfig().getOauth().getPathToP12KeyFile())) {
    File p12KeyFile = new File(getConfig().getOauth().getPathToP12KeyFile());
    if (p12KeyFile.exists() && p12KeyFile.isFile() && p12KeyFile.canRead()) {
      credentialBuilder = credentialBuilder.setServiceAccountPrivateKeyFromP12File(p12KeyFile);
    }
  }
  Credential credential = credentialBuilder.build();
  return new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName("Streams Application").build();
}
 
Example #4
Source File: GetPlaylistTask.java    From SkyTube with GNU General Public License v3.0 6 votes vote down vote up
private YouTubePlaylist getFirstPlaylist(YouTube.Playlists.List api) {
    List<Playlist> playlistList = null;
    try {
        // communicate with YouTube
        PlaylistListResponse listResponse = api.execute();

        // get playlists
        playlistList = listResponse.getItems();

        if (!playlistList.isEmpty()) {
            Playlist playlist = playlistList.get(0);
            YouTubeChannel channel = channelInfo.getChannelInfoSync(playlist.getSnippet().getChannelId());
            return new YouTubePlaylist(playlist, channel);
        }
        // set the next page token

    } catch (IOException ex) {
        Logger.d(this, ex.getLocalizedMessage());
    }

    return null;
}
 
Example #5
Source File: GetPlaylistTask.java    From SkyTube with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected YouTubePlaylist doInBackground(Void... voids) {
    try {
        YouTube.Playlists.List playlistList = YouTubeAPI.create().playlists().list("id, snippet, contentDetails");
        playlistList.setKey(YouTubeAPIKey.get().getYouTubeAPIKey());
        playlistList.setFields("items(id, snippet/title, snippet/description, snippet/thumbnails, snippet/publishedAt, contentDetails/itemCount, snippet/channelId)," +
                "nextPageToken");
        playlistList.setMaxResults(MAX_RESULTS);
        playlistList.setId(playlistId);

        return getFirstPlaylist(playlistList);
    } catch (Exception e) {
        Logger.e(this, "Couldn't initialize GetPlaylist", e);
        lastException = e;
    }
    return null;
}
 
Example #6
Source File: YouTubeAPI.java    From UTubeTV with The Unlicense 6 votes vote down vote up
public YouTube youTube() {
  if (youTube == null) {
    try {
      HttpRequestInitializer credentials;

      if (mUseAuthCredentials)
        credentials = Auth.getCredentials(mContext, mUseDefaultAccount);
      else
        credentials = Auth.nullCredentials(mContext);

      youTube = new YouTube.Builder(new NetHttpTransport(), new AndroidJsonFactory(), credentials).setApplicationName("YouTubeAPI")
          .build();
    } catch (Exception e) {
      e.printStackTrace();
    } catch (Throwable t) {
      t.printStackTrace();
    }
  }

  return youTube;
}
 
Example #7
Source File: YouTubeServiceImpl.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public List<SearchResult> searchChannel(String queryTerm, long maxResults) {
    try {
        SearchResult result = probeSearchByChannelUrl(queryTerm);
        if (result != null) {
            return Collections.singletonList(result);
        }
        YouTube.Search.List search = youTube.search().list("id,snippet");
        search.setKey(getApiKey());
        search.setQ(queryTerm);
        search.setType("channel");
        search.setFields("items(id/channelId, snippet/channelTitle, snippet/thumbnails/default)");
        search.setMaxResults(maxResults);
        return search.execute().getItems();
    } catch (IOException e) {
        log.error("Could not perform YouTube search", e);
    }
    return Collections.emptyList();
}
 
Example #8
Source File: ChatService.java    From youtube-chat-for-minecraft with Apache License 2.0 6 votes vote down vote up
public void deleteMessage(final String messageId, final Runnable onComplete) {
  if (messageId == null || messageId.isEmpty() || executor == null) {
    onComplete.run();
    return;
  }

  executor.execute(
      new Runnable() {
        @Override
        public void run() {
          try {
            YouTube.LiveChatMessages.Delete liveChatDelete =
                youtube.liveChatMessages().delete(messageId);
            liveChatDelete.execute();
            Minecraft.getMinecraft().addScheduledTask(onComplete);
          } catch (Throwable t) {
            showMessage(t.getMessage(), Minecraft.getMinecraft().player);
            t.printStackTrace();
            onComplete.run();
          }
        }
      });
}
 
Example #9
Source File: YoutubeUserActivityCollectorTest.java    From streams with Apache License 2.0 6 votes vote down vote up
private YouTube.Videos.List createMockVideosList(int numBefore, int numAfter, int numInRange, DateTime after, DateTime before) {
  YouTube.Videos.List list = mock(YouTube.Videos.List.class);

  when(list.setMaxResults(anyLong())).thenReturn(list);
  when(list.setPageToken(anyString())).thenReturn(list);
  when(list.setId(anyString())).thenReturn(list);
  when(list.setKey(anyString())).thenReturn(list);

  VideoListResponseAnswer answer = new VideoListResponseAnswer(numBefore, numAfter, numInRange, after, before);
  try {
    doAnswer(answer).when(list).execute();
  } catch (IOException ioe) {
    fail("Should not have thrown exception while creating mock. : " + ioe.getMessage());
  }

  return list;
}
 
Example #10
Source File: ExploreActivity.java    From wmn-safety with MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_explore);

    if (savedInstanceState == null) {
        mYoutubeDataApi = new YouTube.Builder(mTransport, mJsonFactory, null)
                .setApplicationName(getResources().getString(R.string.app_name))
                .build();

        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, ExploreFragment.newInstance(mYoutubeDataApi, YOUTUBE_PLAYLISTS))
                .commit();
    }

}
 
Example #11
Source File: YoutubeChannelDataCollectorTest.java    From streams with Apache License 2.0 6 votes vote down vote up
@Test
public void testDataCollector() throws Exception {
  YouTube youTube = createMockYoutube();
  BlockingQueue<StreamsDatum> queue = new LinkedBlockingQueue<>();
  BackOffStrategy strategy = new LinearTimeBackOffStrategy(1);
  UserInfo userInfo = new UserInfo();
  userInfo.setUserId(ID);
  YoutubeConfiguration config = new YoutubeConfiguration();
  config.setApiKey(ID);
  YoutubeChannelDataCollector collector = new YoutubeChannelDataCollector(youTube, queue, strategy, userInfo, config);
  collector.run();
  assertEquals(1, queue.size());
  StreamsDatum datum = queue.take();
  assertNotNull(datum);
  String document = (String) datum.getDocument();
  assertNotNull(document);
}
 
Example #12
Source File: YoutubeUserActivityCollectorTest.java    From streams with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessActivityFeedMismatchCountInRange() throws IOException, InterruptedException {
  DateTime now = new DateTime(System.currentTimeMillis());
  YouTube youtube = buildYouTube(5, 5, 5, now, now.minus(100000));

  BlockingQueue<StreamsDatum> datumQueue = new ThroughputQueue<>();
  YoutubeUserActivityCollector collector = new YoutubeUserActivityCollector(youtube, datumQueue, new ExponentialBackOffStrategy(2), new UserInfo().withUserId(USER_ID), this.config);

  ActivityListResponse feed = buildActivityListResponse(1);

  collector.processActivityFeed(feed, new DateTime(now), new DateTime(now).minus(100000));

  assertEquals(collector.getDatumQueue().size(), 5);
}
 
Example #13
Source File: YoutubeUserActivityCollectorTest.java    From streams with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessActivityFeedMismatchCount() throws IOException, InterruptedException {
  DateTime now = new DateTime(System.currentTimeMillis());
  YouTube youtube = buildYouTube(5, 5, 5, now, now.minus(100000));

  BlockingQueue<StreamsDatum> datumQueue = new ThroughputQueue<>();
  YoutubeUserActivityCollector collector = new YoutubeUserActivityCollector(youtube, datumQueue, new ExponentialBackOffStrategy(2), new UserInfo().withUserId(USER_ID), this.config);

  ActivityListResponse feed = buildActivityListResponse(1);

  collector.processActivityFeed(feed, new DateTime(now), null);

  assertEquals(collector.getDatumQueue().size(), 5);
}
 
Example #14
Source File: YoutubeChannelDataCollectorTest.java    From streams with Apache License 2.0 5 votes vote down vote up
private YouTube.Channels.List createMockChannelsList() throws Exception {
  YouTube.Channels.List mockList = mock(YouTube.Channels.List.class);
  when(mockList.setId(anyString())).thenReturn(mockList);
  when(mockList.setKey(anyString())).thenReturn(mockList);
  ChannelListResponse response = createMockResponse();
  when(mockList.execute()).thenReturn(response);
  return mockList;
}
 
Example #15
Source File: ExploreFragment.java    From wmn-safety with MIT License 5 votes vote down vote up
public static ExploreFragment newInstance(YouTube youTubeDataApi, String[] playlistIds) {
    ExploreFragment fragment = new ExploreFragment();
    Bundle args = new Bundle();
    args.putStringArray(ARG_YOUTUBE_PLAYLIST_IDS, playlistIds);
    fragment.setArguments(args);
    fragment.setYouTubeDataApi(youTubeDataApi);
    return fragment;
}
 
Example #16
Source File: YoutubeUserActivityCollectorTest.java    From streams with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessActivityFeedAfter() throws IOException, InterruptedException {
  DateTime now = new DateTime(System.currentTimeMillis());
  YouTube youtube = buildYouTube(0, 5, 0, now, now);

  BlockingQueue<StreamsDatum> datumQueue = new ThroughputQueue<>();
  YoutubeUserActivityCollector collector = new YoutubeUserActivityCollector(youtube, datumQueue, new ExponentialBackOffStrategy(2), new UserInfo().withUserId(USER_ID), this.config);

  ActivityListResponse feed = buildActivityListResponse(1);

  collector.processActivityFeed(feed, new DateTime(now.getMillis() - 100000), null);

  assertEquals(collector.getDatumQueue().size(), 5);
}
 
Example #17
Source File: YoutubeUserActivityCollectorTest.java    From streams with Apache License 2.0 5 votes vote down vote up
private YouTube createYoutubeMock(int numBefore, int numAfter, int numInRange, DateTime after, DateTime before) {
  YouTube youtube = mock(YouTube.class);

  final YouTube.Videos videos = createMockVideos(numBefore, numAfter, numInRange, after, before);
  doAnswer(invocationOnMock -> videos).when(youtube).videos();

  return youtube;
}
 
Example #18
Source File: YoutubeUserActivityCollectorTest.java    From streams with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessActivityFeedBefore() throws IOException, InterruptedException {
  DateTime now = new DateTime(System.currentTimeMillis());
  YouTube youtube = buildYouTube(5, 0, 0, now, now);

  BlockingQueue<StreamsDatum> datumQueue = new ThroughputQueue<>();
  YoutubeUserActivityCollector collector = new YoutubeUserActivityCollector(youtube, datumQueue, new ExponentialBackOffStrategy(2), new UserInfo().withUserId(USER_ID), this.config);

  ActivityListResponse feed = buildActivityListResponse(1);

  collector.processActivityFeed(feed, new DateTime(System.currentTimeMillis()), null);

  assertEquals(collector.getDatumQueue().size(), 0);
}
 
Example #19
Source File: YoutubeUserActivityCollectorTest.java    From streams with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessActivityFeed() throws IOException, InterruptedException {
  DateTime now = new DateTime(System.currentTimeMillis());
  YouTube youtube = buildYouTube(0, 0, 5, now.plus(3000000), now.minus(1000000));

  BlockingQueue<StreamsDatum> datumQueue = new ThroughputQueue<>();
  YoutubeUserActivityCollector collector = new YoutubeUserActivityCollector(youtube, datumQueue, new ExponentialBackOffStrategy(2), new UserInfo().withUserId(USER_ID), this.config);

  ActivityListResponse feed = buildActivityListResponse(1);

  collector.processActivityFeed(feed, new DateTime(System.currentTimeMillis()), null);

  assertEquals(collector.getDatumQueue().size(), 5);
}
 
Example #20
Source File: YoutubeUserActivityCollectorTest.java    From streams with Apache License 2.0 5 votes vote down vote up
private YouTube.Videos createMockVideos(int numBefore, int numAfter, int numInRange, DateTime after, DateTime before) {
  YouTube.Videos videos = mock(YouTube.Videos.class);

  try {
    YouTube.Videos.List list = createMockVideosList(numBefore, numAfter, numInRange, after, before);
    when(videos.list(anyString())).thenReturn(list);
  } catch (IOException ex) {
    fail("Exception thrown while creating mock");
  }

  return videos;
}
 
Example #21
Source File: YoutubeUserActivityCollectorTest.java    From streams with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetVideosNull() throws IOException {
  DateTime now = new DateTime(System.currentTimeMillis());
  YouTube youtube = buildYouTube(0, 0, 0, now.plus(10000), now.minus(10000));

  BlockingQueue<StreamsDatum> datumQueue = new ThroughputQueue<>();
  YoutubeUserActivityCollector collector = new YoutubeUserActivityCollector(youtube, datumQueue, new ExponentialBackOffStrategy(2), new UserInfo().withUserId(USER_ID), this.config);

  List<Video> video = collector.getVideoList("fake_video_id");

  assertEquals(video.size(), 0);
}
 
Example #22
Source File: YoutubeUserActivityCollectorTest.java    From streams with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetVideos() throws IOException {
  DateTime now = new DateTime(System.currentTimeMillis());
  YouTube youtube = buildYouTube(0, 1, 0, now, now.minus(10000));

  BlockingQueue<StreamsDatum> datumQueue = new ThroughputQueue<>();
  YoutubeUserActivityCollector collector = new YoutubeUserActivityCollector(youtube, datumQueue, new ExponentialBackOffStrategy(2), new UserInfo().withUserId(USER_ID), this.config);

  List<Video> video = collector.getVideoList("fake_video_id");

  assertNotNull(video.get(0));
}
 
Example #23
Source File: YoutubeUserActivityCollector.java    From streams with Apache License 2.0 5 votes vote down vote up
/**
 * YoutubeUserActivityCollector constructor.
 * @param youtube YouTube
 * @param datumQueue BlockingQueue of StreamsDatum
 * @param backOff BackOffStrategy
 * @param userInfo UserInfo
 * @param config YoutubeConfiguration
 */
public YoutubeUserActivityCollector(
    YouTube youtube,
    BlockingQueue<StreamsDatum> datumQueue,
    BackOffStrategy backOff,
    UserInfo userInfo,
    YoutubeConfiguration config) {
  this.youtube = youtube;
  this.datumQueue = datumQueue;
  this.backOff = backOff;
  this.userInfo = userInfo;
  this.config = config;
}
 
Example #24
Source File: YoutubeChannelDataCollector.java    From streams with Apache License 2.0 5 votes vote down vote up
/**
 * YoutubeChannelDataCollector constructor.
 * @param youTube       YouTube
 * @param queue         BlockingQueue of StreamsDatum
 * @param strategy      BackOffStrategy
 * @param userInfo      UserInfo
 * @param youtubeConfig YoutubeConfiguration
 */
public YoutubeChannelDataCollector(
    YouTube youTube,
    BlockingQueue<StreamsDatum> queue,
    BackOffStrategy strategy,
    UserInfo userInfo,
    YoutubeConfiguration youtubeConfig) {
  this.youTube = youTube;
  this.queue = queue;
  this.strategy = strategy;
  this.userInfo = userInfo;
  this.youtubeConfig = youtubeConfig;
}
 
Example #25
Source File: YouTubeActivity.java    From YouTubePlaylist with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.youtube_activity);

    
    if(!isConnected()){
        Toast.makeText(YouTubeActivity.this,"No Internet Connection Detected",Toast.LENGTH_LONG).show();
    }
    
    if (ApiKey.YOUTUBE_API_KEY.startsWith("YOUR_API_KEY")) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
            .setMessage("Edit ApiKey.java and replace \"YOUR_API_KEY\" with your Applications Browser API Key")
                    .setTitle("Missing API Key")
                    .setNeutralButton("Ok, I got it!", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            finish();
                        }
                    });

        AlertDialog dialog = builder.create();
        dialog.show();

    } else if (savedInstanceState == null) {
        mYoutubeDataApi = new YouTube.Builder(mTransport, mJsonFactory, null)
                .setApplicationName(getResources().getString(R.string.app_name))
                .build();

        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, YouTubeRecyclerViewFragment.newInstance(mYoutubeDataApi, YOUTUBE_PLAYLISTS))
                .commit();
    }
}
 
Example #26
Source File: YouTubeAPI.java    From SkyTube with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a new instance of {@link YouTube}.
 *
 * @return {@link YouTube}
 */
public static YouTube create() {
	HttpTransport httpTransport = AndroidHttp.newCompatibleTransport();
	JsonFactory jsonFactory = com.google.api.client.extensions.android.json.AndroidJsonFactory.getDefaultInstance();
	return new YouTube.Builder(httpTransport, jsonFactory, new HttpRequestInitializer() {
		private String getSha1() {
			String sha1 = null;
			try {
				Signature[] signatures = SkyTubeApp.getContext().getPackageManager().getPackageInfo(BuildConfig.APPLICATION_ID, PackageManager.GET_SIGNATURES).signatures;
				for (Signature signature: signatures) {
					MessageDigest md = MessageDigest.getInstance("SHA-1");

					md.update(signature.toByteArray());
					sha1 = BaseEncoding.base16().encode(md.digest());
				}
			} catch (Throwable tr) {
				Logger.e(this, "...", tr);
			}
			return sha1;
		}
		@Override
		public void initialize(HttpRequest request) throws IOException {
			request.getHeaders().set("X-Android-Package", BuildConfig.APPLICATION_ID);
			request.getHeaders().set("X-Android-Cert", getSha1());
		}
	}).setApplicationName("+").build();
}
 
Example #27
Source File: YoutubeExampleApplication.java    From RxTube with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
  super.onCreate();

  // For more customization, look into this method and use it's code as starter.
  YouTube youtube = YouTubeUtil.createDefaultYouTube("youtube-example-application");
  rxTube = new RxTube(youtube, BuildConfig.YOUTUBE_BROWSER_DEV_KEY);
}
 
Example #28
Source File: YouTubeServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@PostConstruct
public void init() {
    try {
        youTube = new YouTube
                .Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), e -> {
        })
                .setApplicationName(YouTubeServiceImpl.class.getSimpleName())
                .build();
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}
 
Example #29
Source File: YouTubeServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public Video load(String token) {
    String[] parts = token.split("/");
    String videoId = parts[0];
    String part = parts[1];
    try {
        YouTube.Videos.List list = youTube.videos().list(part);
        list.setKey(getApiKey());
        list.setId(videoId);
        List<Video> items = list.execute().getItems();
        return CollectionUtils.isNotEmpty(items) ? items.get(0) : null;
    } catch (IOException e) {
        log.error("Could not get video by id={}", videoId, e);
    }
    return null;
}
 
Example #30
Source File: YouTubeRecyclerViewFragment.java    From YouTubePlaylist with Apache License 2.0 5 votes vote down vote up
/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param youTubeDataApi
 * @param playlistIds A String array of YouTube Playlist IDs
 * @return A new instance of fragment YouTubeRecyclerViewFragment.
 */
public static YouTubeRecyclerViewFragment newInstance(YouTube youTubeDataApi, String[] playlistIds) {
    YouTubeRecyclerViewFragment fragment = new YouTubeRecyclerViewFragment();
    Bundle args = new Bundle();
    args.putStringArray(ARG_YOUTUBE_PLAYLIST_IDS, playlistIds);
    fragment.setArguments(args);
    fragment.setYouTubeDataApi(youTubeDataApi);
    return fragment;
}