my-youtube-api 1.0.4 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,367 @@
1
+ // src/youtube-handlers/youtube-video-poster.ts
2
+ import { google } from "googleapis";
3
+ import axios from "axios";
4
+ import { Readable } from "stream";
5
+ import { YouTubeApiError, YouTubeAuthenticationError, YouTubeQuotaError, YouTubeRateLimitError, YouTubeMediaError, YouTubeUploadError, YouTubeValidationError, YouTubeProcessingError, YouTubeTimeoutError } from "../errors/youtube-api-errors";
6
+ export class YoutubeVideoPoster {
7
+ constructor(access_token) {
8
+ this.access_token = access_token;
9
+ if (!access_token) {
10
+ throw new YouTubeAuthenticationError('Access token is required');
11
+ }
12
+ this.youtube = google.youtube({ version: "v3", auth: this.access_token });
13
+ }
14
+ /**
15
+ * Handle YouTube API errors and throw appropriate custom errors
16
+ */
17
+ handleYouTubeError(error, context) {
18
+ // Handle Google API errors
19
+ if (error.errors && Array.isArray(error.errors)) {
20
+ const apiError = error.errors[0];
21
+ const message = `${context}: ${apiError.message}`;
22
+ const reason = apiError.reason;
23
+ const domain = apiError.domain;
24
+ switch (reason) {
25
+ case 'authError':
26
+ case 'invalidCredentials':
27
+ case 'required':
28
+ throw new YouTubeAuthenticationError(message, apiError);
29
+ case 'quotaExceeded':
30
+ case 'dailyLimitExceeded':
31
+ case 'userRateLimitExceeded':
32
+ throw new YouTubeQuotaError(message, apiError);
33
+ case 'rateLimitExceeded':
34
+ case 'userRateLimitExceeded':
35
+ throw new YouTubeRateLimitError(message, apiError);
36
+ case 'invalidValue':
37
+ case 'invalid':
38
+ throw new YouTubeValidationError(message, apiError);
39
+ case 'processingFailed':
40
+ case 'failed':
41
+ throw new YouTubeProcessingError(message, apiError);
42
+ default:
43
+ throw new YouTubeApiError(message, `YOUTUBE_${reason?.toUpperCase()}`, error.code, apiError);
44
+ }
45
+ }
46
+ // Handle axios/network errors
47
+ if (error.response?.data?.error) {
48
+ const youtubeError = error.response.data.error;
49
+ const message = `${context}: ${youtubeError.message}`;
50
+ const code = youtubeError.code;
51
+ switch (code) {
52
+ case 401:
53
+ case 403:
54
+ throw new YouTubeAuthenticationError(message, youtubeError);
55
+ case 429:
56
+ throw new YouTubeRateLimitError(message, youtubeError);
57
+ case 400:
58
+ throw new YouTubeValidationError(message, youtubeError);
59
+ case 500:
60
+ case 503:
61
+ throw new YouTubeProcessingError(message, youtubeError);
62
+ default:
63
+ throw new YouTubeApiError(message, `YOUTUBE_${code}`, code, youtubeError);
64
+ }
65
+ }
66
+ // Handle timeout errors
67
+ if (error.code === 'ECONNABORTED' || error.message?.includes('timeout')) {
68
+ throw new YouTubeTimeoutError(`${context}: Request timed out`, error);
69
+ }
70
+ // Handle network errors
71
+ if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {
72
+ throw new YouTubeApiError(`${context}: Network error - ${error.message}`, 'NETWORK_ERROR', 503);
73
+ }
74
+ // Handle media/upload specific errors
75
+ if (error.message?.includes('stream') || error.message?.includes('video') || error.message?.includes('upload')) {
76
+ throw new YouTubeUploadError(`${context}: ${error.message}`, error);
77
+ }
78
+ // Default to generic API error
79
+ if (error instanceof YouTubeApiError) {
80
+ throw error;
81
+ }
82
+ throw new YouTubeApiError(`${context}: ${error.message}`, 'UNKNOWN_ERROR', error.response?.status);
83
+ }
84
+ /**
85
+ * Validate video metadata
86
+ */
87
+ validateMetadata(metadata) {
88
+ if (!metadata.title || metadata.title.trim().length === 0) {
89
+ throw new YouTubeValidationError('Video title is required');
90
+ }
91
+ if (metadata.title.length > 100) {
92
+ throw new YouTubeValidationError('Video title must be 100 characters or less');
93
+ }
94
+ if (metadata.description && metadata.description.length > 5000) {
95
+ throw new YouTubeValidationError('Video description must be 5000 characters or less');
96
+ }
97
+ if (metadata.tags && metadata.tags.length > 500) {
98
+ throw new YouTubeValidationError('Maximum 500 tags allowed');
99
+ }
100
+ if (metadata.tags) {
101
+ for (const tag of metadata.tags) {
102
+ if (tag.length > 30) {
103
+ throw new YouTubeValidationError(`Tag "${tag}" must be 30 characters or less`);
104
+ }
105
+ }
106
+ }
107
+ const validPrivacyStatuses = ['public', 'private', 'unlisted'];
108
+ if (metadata.privacyStatus && !validPrivacyStatuses.includes(metadata.privacyStatus)) {
109
+ throw new YouTubeValidationError(`Privacy status must be one of: ${validPrivacyStatuses.join(', ')}`);
110
+ }
111
+ const validLicenses = ['youtube', 'creativeCommon'];
112
+ if (metadata.license && !validLicenses.includes(metadata.license)) {
113
+ throw new YouTubeValidationError(`License must be one of: ${validLicenses.join(', ')}`);
114
+ }
115
+ }
116
+ /**
117
+ * Fetch video stream from URL with proper error handling
118
+ */
119
+ async fetchVideoStream(videoUrl) {
120
+ try {
121
+ console.log(`📹 Fetching video from: ${videoUrl}`);
122
+ const response = await axios.get(videoUrl, {
123
+ responseType: "stream",
124
+ timeout: 30000, // 30 second timeout
125
+ maxContentLength: 1024 * 1024 * 1024, // 1GB max file size
126
+ validateStatus: (status) => status === 200
127
+ });
128
+ if (!response.data || !(response.data instanceof Readable)) {
129
+ throw new YouTubeMediaError('Invalid video stream received from URL');
130
+ }
131
+ return response.data;
132
+ }
133
+ catch (error) {
134
+ if (error instanceof YouTubeApiError) {
135
+ throw error;
136
+ }
137
+ if (error.response?.status === 404) {
138
+ throw new YouTubeMediaError(`Video not found at URL: ${videoUrl}`);
139
+ }
140
+ else if (error.response?.status === 403) {
141
+ throw new YouTubeMediaError(`Access denied to video URL: ${videoUrl}`);
142
+ }
143
+ else if (error.code === 'ECONNABORTED') {
144
+ throw new YouTubeTimeoutError(`Timeout while fetching video from URL: ${videoUrl}`);
145
+ }
146
+ else {
147
+ throw new YouTubeMediaError(`Failed to fetch video from URL: ${error.message}`);
148
+ }
149
+ }
150
+ }
151
+ /**
152
+ * Wait for video processing to complete
153
+ */
154
+ async waitForVideoProcessing(videoId, timeoutMs = 300000 // 5 minutes
155
+ ) {
156
+ const startTime = Date.now();
157
+ const maxAttempts = 30;
158
+ let attempts = 0;
159
+ console.log(`⏳ Waiting for video processing: ${videoId}`);
160
+ while (attempts < maxAttempts && Date.now() - startTime < timeoutMs) {
161
+ attempts++;
162
+ try {
163
+ const statusResponse = await this.youtube.videos.list({
164
+ part: ['status'],
165
+ id: [videoId]
166
+ });
167
+ const video = statusResponse.data.items?.[0];
168
+ if (!video) {
169
+ throw new YouTubeProcessingError(`Video ${videoId} not found after upload`);
170
+ }
171
+ const status = video.status?.uploadStatus;
172
+ switch (status) {
173
+ case 'processed':
174
+ console.log(`✅ Video processing completed: ${videoId}`);
175
+ return;
176
+ case 'failed':
177
+ const failureReason = video.status?.failureReason || 'Unknown failure reason';
178
+ throw new YouTubeProcessingError(`Video processing failed: ${failureReason}`);
179
+ case 'rejected':
180
+ const rejectionReason = video.status?.rejectionReason || 'Unknown rejection reason';
181
+ throw new YouTubeProcessingError(`Video was rejected: ${rejectionReason}`);
182
+ case 'uploaded':
183
+ case 'processing':
184
+ // Wait and check again
185
+ const waitTime = Math.min(1000 * Math.pow(2, attempts), 10000); // Exponential backoff, max 10s
186
+ console.log(`⏳ Video status: ${status}, waiting ${waitTime}ms...`);
187
+ await new Promise(resolve => setTimeout(resolve, waitTime));
188
+ break;
189
+ default:
190
+ await new Promise(resolve => setTimeout(resolve, 5000));
191
+ break;
192
+ }
193
+ }
194
+ catch (error) {
195
+ if (error instanceof YouTubeApiError) {
196
+ throw error;
197
+ }
198
+ this.handleYouTubeError(error, "Failed to check video processing status");
199
+ }
200
+ }
201
+ throw new YouTubeTimeoutError(`Video processing timed out after ${timeoutMs}ms`);
202
+ }
203
+ /**
204
+ * Add video to playlist if specified
205
+ */
206
+ async addToPlaylist(videoId, playlistId) {
207
+ try {
208
+ await this.youtube.playlistItems.insert({
209
+ part: ['snippet'],
210
+ requestBody: {
211
+ snippet: {
212
+ playlistId: playlistId,
213
+ resourceId: {
214
+ kind: 'youtube#video',
215
+ videoId: videoId
216
+ }
217
+ }
218
+ }
219
+ });
220
+ console.log(`✅ Video ${videoId} added to playlist ${playlistId}`);
221
+ }
222
+ catch (error) {
223
+ console.warn(`⚠️ Failed to add video to playlist: ${error.message}`);
224
+ // Don't throw error for playlist addition failure as video upload was successful
225
+ }
226
+ }
227
+ /**
228
+ * Upload a video from a Cloudinary URL to YouTube
229
+ */
230
+ async uploadFromCloudUrl2(videoUrl, metadata) {
231
+ let videoStream = null;
232
+ try {
233
+ // Validate metadata first
234
+ this.validateMetadata(metadata);
235
+ // Fetch video stream
236
+ videoStream = await this.fetchVideoStream(videoUrl);
237
+ // Prepare metadata payload
238
+ const metadataPayload = {
239
+ part: ["snippet", "status"],
240
+ notifySubscribers: metadata.notifySubscribers !== false,
241
+ requestBody: {
242
+ snippet: {
243
+ title: metadata.title.substring(0, 100),
244
+ description: (metadata.description || "").substring(0, 5000),
245
+ tags: (metadata.tags || []).slice(0, 500),
246
+ categoryId: metadata.categoryId || "22"
247
+ },
248
+ status: {
249
+ privacyStatus: metadata.privacyStatus || "private",
250
+ embeddable: metadata.embeddable !== false,
251
+ publicStatsViewable: metadata.publicStatsViewable !== false,
252
+ license: metadata.license || "youtube",
253
+ selfDeclaredMadeForKids: metadata.madeForKids || false
254
+ }
255
+ },
256
+ media: { body: videoStream }
257
+ };
258
+ console.log(`🚀 Uploading video to YouTube: "${metadata.title}"`);
259
+ // Upload video
260
+ const uploadResponse = await this.youtube.videos.insert(metadataPayload)
261
+ .catch(error => this.handleYouTubeError(error, "Failed to upload video to YouTube"));
262
+ const videoId = uploadResponse.data.id;
263
+ if (!videoId) {
264
+ throw new YouTubeUploadError('Video ID not returned from YouTube API');
265
+ }
266
+ console.log(`✅ Video uploaded successfully: ${videoId}`);
267
+ // Wait for processing to complete
268
+ await this.waitForVideoProcessing(videoId);
269
+ // Add to playlist if specified
270
+ if (metadata.playlistId) {
271
+ await this.addToPlaylist(videoId, metadata.playlistId);
272
+ }
273
+ const result = {
274
+ id: videoId,
275
+ status: 'processed',
276
+ url: `https://www.youtube.com/watch?v=${videoId}`,
277
+ title: metadata.title,
278
+ description: metadata.description,
279
+ // You can add thumbnail URL here if needed
280
+ };
281
+ console.log(`🎉 YouTube video published successfully: ${result.url}`);
282
+ return result;
283
+ }
284
+ catch (error) {
285
+ // Clean up stream if it exists
286
+ if (videoStream) {
287
+ videoStream.destroy();
288
+ }
289
+ if (error instanceof YouTubeApiError) {
290
+ throw error;
291
+ }
292
+ this.handleYouTubeError(error, "Unexpected error during YouTube video upload");
293
+ }
294
+ }
295
+ /**
296
+ * Upload a video from a Cloudinary URL to YouTube
297
+ * @param videoUrl URL of the video on Cloudinary
298
+ * @param metadata Video metadata
299
+ */
300
+ async uploadFromCloudUrl(videoUrl, metadata) {
301
+ try {
302
+ // Fetch video as stream from Cloudinary
303
+ const response = await axios.get(videoUrl, { responseType: "stream" });
304
+ const videoStream = response.data;
305
+ // Prepare metadata payload
306
+ const metadataPayload = {
307
+ part: ["snippet", "status"],
308
+ requestBody: {
309
+ snippet: {
310
+ title: metadata.title.substring(0, 100),
311
+ description: (metadata.description || "").substring(0, 5000),
312
+ tags: (metadata.tags || []).slice(0, 5),
313
+ categoryId: metadata.categoryId || "22"
314
+ },
315
+ status: {
316
+ privacyStatus: metadata.privacyStatus || "private",
317
+ embeddable: metadata.embeddable !== false,
318
+ publicStatsViewable: metadata.publicStatsViewable !== false,
319
+ license: metadata.license || "youtube",
320
+ selfDeclaredMadeForKids: metadata.madeForKids || false
321
+ }
322
+ },
323
+ media: { body: videoStream }
324
+ };
325
+ // Upload video
326
+ const res = await this.youtube.videos.insert(metadataPayload);
327
+ return res.data;
328
+ }
329
+ catch (error) {
330
+ console.error("YouTube upload failed:", error.response?.data || error.message);
331
+ throw new Error(`YouTube upload failed: ${error.response?.data?.error?.message || error.message}`);
332
+ }
333
+ }
334
+ /**
335
+ * Get video details
336
+ */
337
+ async getVideoDetails(videoId) {
338
+ try {
339
+ const response = await this.youtube.videos.list({
340
+ part: ['snippet', 'status', 'contentDetails', 'statistics'],
341
+ id: [videoId]
342
+ });
343
+ const video = response.data.items?.[0];
344
+ if (!video) {
345
+ throw new YouTubeValidationError(`Video not found: ${videoId}`);
346
+ }
347
+ return video;
348
+ }
349
+ catch (error) {
350
+ this.handleYouTubeError(error, "Failed to get video details");
351
+ }
352
+ }
353
+ /**
354
+ * Delete a video
355
+ */
356
+ async deleteVideo(videoId) {
357
+ try {
358
+ await this.youtube.videos.delete({
359
+ id: videoId
360
+ });
361
+ console.log(`✅ Video deleted successfully: ${videoId}`);
362
+ }
363
+ catch (error) {
364
+ this.handleYouTubeError(error, "Failed to delete video");
365
+ }
366
+ }
367
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-youtube-api",
3
- "version": "1.0.4",
3
+ "version": "1.0.6",
4
4
  "main": "dist/index.js",
5
5
  "scripts": {
6
6
  "prepublishOnly": "npm run build",