Class YouTube
- All Implemented Interfaces:
ContextProvider, PropertyChangeSource, Rebindable
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 Summary
FieldsModifier and TypeFieldDescriptionprivate ScreenRecorderActive standalone screen recorder instance.private static final HttpClientShared HTTP client configured with a 30-second connect timeout and HTTP/2 support.private static final com.fasterxml.jackson.databind.ObjectMapperShared JSON object mapper for request serialization and response parsing.private static final StringYouTube playlist items API endpoint URL.private static final StringYouTube playlists collection endpoint URL (for playlist creation and lookup).private static final StringYouTube custom thumbnail upload endpoint URL.private static final StringResumable upload initiation endpoint URL for YouTube Data API v3.Fields inherited from class AnahataToolkit
childrenProviders, propertyChangeSupportFields inherited from class ToolContext
toolkit -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionaddVideoToPlaylist(String videoId, String playlistId) Adds an existing YouTube video to a specified playlist.private voidaddVideoToPlaylistInternal(String accessToken, String videoId, String playlistId) Adds an uploaded video to a YouTube playlist via playlistItems API.createPlaylist(String title, String description) Creates a brand-new YouTube playlist owned by the authenticated channel.private StringcreatePlaylistInternal(String accessToken, String title, String description) Creates a playlist on the authenticated channel via the playlists collection endpoint.findOrCreatePlaylist(String title, String description) Finds an existing playlist by title (case-insensitive) or creates it if missing, returning its ID.private StringfindPlaylistByTitleInternal(String accessToken, String title) Finds a playlist owned by the authenticated channel whose title matches (case-insensitive).Checks if YouTube OAuth2 credentials are configured and authenticated.getVideoStats(String videoId) Retrieves live statistics and engagement metrics (views, likes, comments) for a YouTube video.voidPerforms initial setup for a newly created toolkit instance.private StringinitializeResumableUpload(String accessToken, YouTubeVideoUploadRequest request, long fileSize) Initiates the resumable upload session with YouTube Data API v3 and retrieves the upload URL.Lists all YouTube playlists owned by the authenticated channel.login()Initiates the 1-click interactive browser login using the official Anahata Desktop OAuth client.loginInteractive(String clientId, String clientSecret, String playlistId) Initiates the interactive browser login flow for YouTube with custom OAuth client credentials.voidpopulateMessage(RagMessage ragMessage) Populates the givenRagMessagewith dynamic, just-in-time context parts.resolveOrCreatePlaylist(String title, String description) Resolves an existing playlist by title or creates it if absent, returning the raw playlist ID.setThumbnail(String videoId, String imagePath) Sets the custom video thumbnail for an uploaded YouTube video.private voidsetThumbnailInternal(String accessToken, String videoId, Path thumbPath) Uploads the thumbnail binary stream to YouTube's thumbnail endpoint.startScreenRecording(String videoTitle, String playlistId, String privacyStatus, String customTargetFilePath) Launches the screen recording overlay to record the screen and publish directly to YouTube.private StringstreamVideoFile(String uploadUrl, Path videoPath, long fileSize) Streams the binary video file content to the resumable upload URL.uploadVideo(YouTubeVideoUploadRequest request) Uploads a video to YouTube using the Resumable Upload protocol.uploadVideoToPlaylist(String videoFilePath, String title, String description, List<String> tags, String playlistId, String privacyStatus) Convenience tool to upload a video with discrete primitive parameters.Methods inherited from class AnahataToolkit
getChildrenProviders, getDescription, getId, getName, getParentProvider, getPropertyChangeSupport, isEffectivelyProviding, postActivate, rebindMethods inherited from class ToolContext
addAttachment, addAttachment, addAttachment, addAttachment, error, error, error, getAgi, getApplicationMap, getAsiContainer, getAsiContainerMap, getCall, getExecutorService, getModelId, getModelMessage, getResourceManager, getResponse, getSessionMap, getThreadSafeLogger, getTool, getToolContext, getToolkit, getToolManager, getTurnMap, isToolExecution, log, peekResponse, runAsyncMethods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface ContextProvider
getAgi, getContextPosition, getFlattenedHierarchy, getFullyQualifiedId, getHeader, getIconId, getInstructionsTokenCount, getRagTokenCount, getSystemInstructions, isProviding, setParentProvider, setProviding
-
Field Details
-
YOUTUBE_UPLOAD_ENDPOINT
Resumable upload initiation endpoint URL for YouTube Data API v3.- See Also:
-
YOUTUBE_THUMBNAIL_ENDPOINT
YouTube custom thumbnail upload endpoint URL.- See Also:
-
YOUTUBE_PLAYLIST_ITEMS_ENDPOINT
YouTube playlist items API endpoint URL.- See Also:
-
YOUTUBE_PLAYLISTS_ENDPOINT
YouTube playlists collection endpoint URL (for playlist creation and lookup).- See Also:
-
MAPPER
private static final com.fasterxml.jackson.databind.ObjectMapper MAPPERShared JSON object mapper for request serialization and response parsing. -
HTTP_CLIENT
Shared HTTP client configured with a 30-second connect timeout and HTTP/2 support. -
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
ToolManagerafter 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:
initializein classAnahataToolkit
-
populateMessage
Populates the givenRagMessagewith 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
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
-
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
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
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
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
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
-
createPlaylist
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
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
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
@AgiToolwrapper) 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
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
nullif 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
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.
-

