Class YouTube

All Implemented Interfaces:
ContextProvider, PropertyChangeSource, Rebindable

public class YouTube extends AnahataToolkit
Pure Java YouTube Data API v3 toolkit providing autonomous video uploads, screen recording publishing, playlist management, and channel analytics.

Implements the official Google YouTube Resumable Upload protocol using standard HttpClient without external client libraries. Integrates with YouTubeAuthHelper for automated OAuth2 token refreshment and browser-based login.

Author:
anahata
  • Field Details

    • YOUTUBE_UPLOAD_ENDPOINT

      private static final String YOUTUBE_UPLOAD_ENDPOINT
      Resumable upload initiation endpoint URL for YouTube Data API v3.
      See Also:
    • YOUTUBE_THUMBNAIL_ENDPOINT

      private static final String YOUTUBE_THUMBNAIL_ENDPOINT
      YouTube custom thumbnail upload endpoint URL.
      See Also:
    • YOUTUBE_PLAYLIST_ITEMS_ENDPOINT

      private static final String YOUTUBE_PLAYLIST_ITEMS_ENDPOINT
      YouTube playlist items API endpoint URL.
      See Also:
    • YOUTUBE_PLAYLISTS_ENDPOINT

      private static final String YOUTUBE_PLAYLISTS_ENDPOINT
      YouTube playlists collection endpoint URL (for playlist creation and lookup).
      See Also:
    • MAPPER

      private static final com.fasterxml.jackson.databind.ObjectMapper MAPPER
      Shared JSON object mapper for request serialization and response parsing.
    • HTTP_CLIENT

      private static final HttpClient HTTP_CLIENT
      Shared HTTP client configured with a 30-second connect timeout and HTTP/2 support.
    • activeRecorder

      private transient ScreenRecorder activeRecorder
      Active standalone screen recorder instance.
  • Constructor Details

    • YouTube

      public YouTube()
      Default constructor for the YouTube toolkit.
  • Method Details

    • initialize

      public void initialize()
      Performs initial setup for a newly created toolkit instance.

      This method is called exactly once by the ToolManager after the toolkit has been instantiated and registered. It provides a clean hook for toolkits to perform one-time initialization logic that requires the tool environment to be fully configured, such as scanning for project instructions or registering default resources.

      Disables the YouTube toolkit on startup by default.

      Overrides:
      initialize in class AnahataToolkit
    • populateMessage

      public void populateMessage(RagMessage ragMessage) throws Exception
      Populates the given RagMessage with dynamic, just-in-time context parts. These parts are appended to the end of the user's prompt (RAG).

      Injects live YouTube channel metadata, statistics, playlists, and recent uploads into the RAG message.

      Parameters:
      ragMessage - The message to be augmented with context.
      Throws:
      Exception - if an error occurs during context generation.
    • startScreenRecording

      public String startScreenRecording(String videoTitle, String playlistId, String privacyStatus, String customTargetFilePath) throws Exception
      Launches the screen recording overlay to record the screen and publish directly to YouTube.
      Parameters:
      videoTitle - The title for the uploaded video.
      playlistId - The optional target playlist ID.
      privacyStatus - The privacy status: "unlisted", "public", or "private".
      Returns:
      Confirmation with resulting video URL upon completion.
      Throws:
      Exception - If recording or upload fails.
    • login

      public String login() throws Exception
      Initiates the 1-click interactive browser login using the official Anahata Desktop OAuth client.

      Launches a local callback listener, opens the user's default browser to Google OAuth consent, exchanges the code for a permanent refresh token, and saves credentials to disk.

      Returns:
      Confirmation message indicating successful authentication.
      Throws:
      Exception - If authorization fails or is cancelled.
    • getAuthStatus

      public String getAuthStatus() throws Exception
      Checks if YouTube OAuth2 credentials are configured and authenticated.
      Returns:
      A status message indicating authentication state.
      Throws:
      Exception - If reading credentials fails.
    • loginInteractive

      public String loginInteractive(String clientId, String clientSecret, String playlistId) throws Exception
      Initiates the interactive browser login flow for YouTube with custom OAuth client credentials.
      Parameters:
      clientId - The optional Google Cloud OAuth 2.0 Client ID.
      clientSecret - The optional Google Cloud OAuth 2.0 Client Secret.
      playlistId - The optional default YouTube playlist ID.
      Returns:
      Confirmation message with saved credentials details.
      Throws:
      Exception - If authentication fails or is cancelled.
    • uploadVideo

      public String uploadVideo(YouTubeVideoUploadRequest request) throws Exception
      Uploads a video to YouTube using the Resumable Upload protocol.
      Parameters:
      request - The upload request containing file path, metadata, tags, and playlist.
      Returns:
      The public or unlisted URL of the uploaded video (e.g. "https://youtu.be/...").
      Throws:
      Exception - If the upload or authorization fails.
    • uploadVideoToPlaylist

      public String uploadVideoToPlaylist(String videoFilePath, String title, String description, List<String> tags, String playlistId, String privacyStatus) throws Exception
      Convenience tool to upload a video with discrete primitive parameters.
      Parameters:
      videoFilePath - The absolute path of the video file.
      title - The video title.
      description - The video description.
      tags - The list of tags.
      playlistId - The optional target playlist ID.
      privacyStatus - The privacy status ("unlisted", "public", "private").
      Returns:
      The resulting YouTube URL.
      Throws:
      Exception - If upload fails.
    • setThumbnail

      public String setThumbnail(String videoId, String imagePath) throws Exception
      Sets the custom video thumbnail for an uploaded YouTube video.
      Parameters:
      videoId - The 11-character YouTube video ID.
      imagePath - The absolute path of the thumbnail image file (.png or .jpg).
      Returns:
      Confirmation message with the video ID.
      Throws:
      Exception - If thumbnail upload or authorization fails.
    • addVideoToPlaylist

      public String addVideoToPlaylist(String videoId, String playlistId) throws Exception
      Adds an existing YouTube video to a specified playlist.
      Parameters:
      videoId - The 11-character YouTube video ID.
      playlistId - The target YouTube playlist ID.
      Returns:
      Confirmation message.
      Throws:
      Exception - If the playlist insertion fails.
    • getVideoStats

      public String getVideoStats(String videoId) throws Exception
      Retrieves live statistics and engagement metrics (views, likes, comments) for a YouTube video.
      Parameters:
      videoId - The 11-character YouTube video ID.
      Returns:
      Formatted statistics report.
      Throws:
      Exception - If querying the YouTube API fails.
    • listPlaylists

      public String listPlaylists() throws Exception
      Lists all YouTube playlists owned by the authenticated channel.
      Returns:
      Formatted list of playlists with IDs, titles, and item counts.
      Throws:
      Exception - If querying playlists fails.
    • createPlaylist

      public String createPlaylist(String title, String description) throws Exception
      Creates a brand-new YouTube playlist owned by the authenticated channel.
      Parameters:
      title - The desired playlist title.
      description - The optional playlist description.
      Returns:
      A confirmation message carrying the new playlist ID.
      Throws:
      Exception - If playlist creation or authorization fails.
    • findOrCreatePlaylist

      public String findOrCreatePlaylist(String title, String description) throws Exception
      Finds an existing playlist by title (case-insensitive) or creates it if missing, returning its ID.

      Provides idempotent playlist resolution so repeated benchmark runs accumulate into a single per-test playlist instead of spawning duplicates.

      Parameters:
      title - The playlist title to find or create.
      description - The optional description applied only when a new playlist is created.
      Returns:
      A message carrying the existing or newly created playlist ID.
      Throws:
      Exception - If the playlist lookup, creation, or authorization fails.
    • resolveOrCreatePlaylist

      public String resolveOrCreatePlaylist(String title, String description) throws Exception
      Resolves an existing playlist by title or creates it if absent, returning the raw playlist ID.

      Exposed as a plain public helper (distinct from the @AgiTool wrapper) so internal orchestrators such as the benchmark engine can obtain the raw ID without parsing a UI message.

      Parameters:
      title - The playlist title to find or create.
      description - The optional description applied only when creating.
      Returns:
      The existing or newly created playlist ID.
      Throws:
      Exception - If authorization, lookup, or creation fails.
    • createPlaylistInternal

      private String createPlaylistInternal(String accessToken, String title, String description) throws Exception
      Creates a playlist on the authenticated channel via the playlists collection endpoint.
      Parameters:
      accessToken - The OAuth2 access token.
      title - The playlist title.
      description - The optional playlist description.
      Returns:
      The new playlist ID.
      Throws:
      Exception - If the API call fails.
    • findPlaylistByTitleInternal

      private String findPlaylistByTitleInternal(String accessToken, String title) throws Exception
      Finds a playlist owned by the authenticated channel whose title matches (case-insensitive).
      Parameters:
      accessToken - The OAuth2 access token.
      title - The title to match.
      Returns:
      The matching playlist ID, or null if not found.
      Throws:
      Exception - If the API call fails.
    • initializeResumableUpload

      private String initializeResumableUpload(String accessToken, YouTubeVideoUploadRequest request, long fileSize) throws Exception
      Initiates the resumable upload session with YouTube Data API v3 and retrieves the upload URL.
      Parameters:
      accessToken - The OAuth2 access token.
      request - The video upload metadata request.
      fileSize - The size of the video file in bytes.
      Returns:
      The resumable upload target URI.
      Throws:
      Exception - If initiation fails.
    • streamVideoFile

      private String streamVideoFile(String uploadUrl, Path videoPath, long fileSize) throws Exception
      Streams the binary video file content to the resumable upload URL.
      Parameters:
      uploadUrl - The upload URL returned by the initialization step.
      videoPath - The path to the local video file.
      fileSize - The size of the file in bytes.
      Returns:
      The extracted YouTube video ID.
      Throws:
      Exception - If binary streaming fails.
    • setThumbnailInternal

      private void setThumbnailInternal(String accessToken, String videoId, Path thumbPath) throws Exception
      Uploads the thumbnail binary stream to YouTube's thumbnail endpoint.
      Parameters:
      accessToken - The OAuth2 access token.
      videoId - The video ID.
      thumbPath - The path to the image file.
      Throws:
      Exception - If thumbnail upload fails.
    • addVideoToPlaylistInternal

      private void addVideoToPlaylistInternal(String accessToken, String videoId, String playlistId) throws Exception
      Adds an uploaded video to a YouTube playlist via playlistItems API.
      Parameters:
      accessToken - The OAuth2 access token.
      videoId - The video ID.
      playlistId - The playlist ID.
      Throws:
      Exception - If insertion fails.