### Setup Script Execution Bash Commands Source: https://github.com/atticdm/getsocialvideobot/blob/main/video-bot/README.md These commands execute the project's setup scripts. The recommended approach uses nvm (Node Version Manager), while a basic setup script is available as an alternative. ```bash # If you have nvm installed (recommended) ./setup.sh # or npm run setup # If you don't have nvm, use basic setup ./setup-basic.sh ``` -------------------------------- ### Production Server Start Bash Command Source: https://github.com/atticdm/getsocialvideobot/blob/main/video-bot/README.md This command sequence builds the project and then starts the main production server, making the bot operational. ```bash npm run build npm start ``` -------------------------------- ### Logging Configuration Example (TypeScript) Source: https://github.com/atticdm/getsocialvideobot/blob/main/video-bot/README.md Illustrates the setup for logging in both development (pretty-printed to console) and production (structured JSON to files). ```typescript src/core/logger.ts import winston from 'winston'; const logger = winston.createLogger({ level: process.env.NODE_ENV === 'production' ? 'info' : 'debug', format: process.env.NODE_ENV === 'production' ? winston.format.json() : winston.format.combine( winston.format.colorize(), winston.format.simple() ), transports: [ new winston.transports.File({ filename: 'logs/error.log', level: 'error' }), new winston.transports.File({ filename: 'logs/app.log' }) ] }); export default logger; ``` -------------------------------- ### Railway Deployment Commands Source: https://github.com/atticdm/getsocialvideobot/blob/main/video-bot/README.md These are example commands and configurations for deploying the application on Railway. They cover the build and start steps, along with setting environment variables. ```bash # Build: npm ci && npm run build # Start: APP_MODE=web PORT=3000 npm start (or npm run start:web if using Nixpacks) ``` -------------------------------- ### Start Local Web Server Bash Commands Source: https://github.com/atticdm/getsocialvideobot/blob/main/video-bot/README.md These commands build the project and then start a local web server, accessible at http://localhost:3000. This is useful for testing the web interface. ```bash npm run build PORT=3000 npm run start:web # open http://localhost:3000 ``` -------------------------------- ### Example Bot Commands Source: https://github.com/atticdm/getsocialvideobot/blob/main/video-bot/README.md These are examples of how to interact with the Telegram bot using specific commands and URLs. They illustrate downloading videos and translating Instagram Reels. ```bash /download https://www.facebook.com/watch/?v=123456789 /download https://fb.watch/abc123def/ /translate https://www.instagram.com/reel/XXXXXXXXXXX/ en-ru ``` -------------------------------- ### Web Server API Start Command (Bash) Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Demonstrates how to start the web server for the bot, typically used for handling webhooks. It requires setting the port and a public URL for the bot's domain, ensuring it can receive external requests. ```bash # Start web server with bot webhook PORT=3000 PUBLIC_URL=https://your-domain.com npm start ``` -------------------------------- ### Install Node.js Dependencies Bash Command Source: https://github.com/atticdm/getsocialvideobot/blob/main/video-bot/README.md This command installs all the necessary Node.js dependencies for the project after the repository has been cloned and the Node.js environment is set up. ```bash npm install ``` -------------------------------- ### Development Server Start Bash Command Source: https://github.com/atticdm/getsocialvideobot/blob/main/video-bot/README.md This command starts the project in development mode, typically enabling hot-reloading and other developer-focused features for rapid iteration. ```bash npm run dev ``` -------------------------------- ### Bot Command Structure Example (TypeScript) Source: https://github.com/atticdm/getsocialvideobot/blob/main/video-bot/README.md Demonstrates the basic structure for bot command handlers within the 'commands' directory. This is a foundational example for extending bot functionality. ```typescript src/bot/commands/example.ts // Example command handler structure import { Message } from 'discord.js'; export default { name: 'example', description: 'An example command', execute(message: Message, args: string[]) { message.reply('This is an example command!'); } }; ``` -------------------------------- ### FFmpeg Remux Command Example (Bash) Source: https://github.com/atticdm/getsocialvideobot/blob/main/video-bot/README.md This is a conceptual example of an ffmpeg command used in the remuxing process, combining audio and video streams after translation. ```bash # Conceptual ffmpeg command for remuxing ffmpeg -i input_video.mp4 -i input_audio.aac -c:v copy -c:a aac -strict experimental output.mp4 ``` -------------------------------- ### Environment Variables Configuration Source: https://github.com/atticdm/getsocialvideobot/blob/main/video-bot/README.md This is an example `.env` file showing the required and optional environment variables for configuring the bot, including API keys, download directories, and feature flags. ```env BOT_TOKEN=your_telegram_bot_token_here NODE_ENV=development DOWNLOAD_DIR=./.tmp MAX_FILE_MB=1950 LOG_LEVEL=info # Enable reel translation (optional) ENABLE_REEL_TRANSLATION=1 OPENAI_API_KEY= OPENAI_WHISPER_MODEL=whisper-1 OPENAI_TRANSLATE_MODEL=gpt-4o-mini HUME_API_KEY= HUME_CLIENT_SECRET= HUME_VOICE_ID=octave-2-evi HUME_AUDIO_FORMAT=wav #FFMPEG_PATH=/usr/bin/ffmpeg ``` -------------------------------- ### Clone Repository Bash Script Source: https://github.com/atticdm/getsocialvideobot/blob/main/video-bot/README.md This script clones the project repository and navigates into the project directory. It's the first step in both quick and manual setup processes. ```bash git clone cd video-bot ``` -------------------------------- ### Run TikTok Integration Tests Source: https://github.com/atticdm/getsocialvideobot/blob/main/docs/TIKTOK_INTEGRATION.md This sequence of bash commands demonstrates how to build the video-bot, start the web server on port 3000, and then execute the integration tests for the TikTok provider. This verifies the end-to-end functionality. ```bash cd video-bot npm run build PORT=3000 npm run start:web & node test-integration.js ``` -------------------------------- ### File System Utilities Example (TypeScript) Source: https://github.com/atticdm/getsocialvideobot/blob/main/video-bot/README.md Provides utility functions for file system operations, such as deleting temporary files to maintain security and manage disk space. ```typescript src/core/fs.ts import * as fs from 'fs/promises'; import * as path from 'path'; export async function cleanupTemporaryFiles(directory: string) { try { const files = await fs.readdir(directory); for (const file of files) { const filePath = path.join(directory, file); await fs.unlink(filePath); } } catch (error) { console.error('Error cleaning up temporary files:', error); } } ``` -------------------------------- ### Local Web Server Testing Command Source: https://github.com/atticdm/getsocialvideobot/blob/main/docs/CONTEXT.md This command demonstrates how to run the web server locally for testing. It specifies the FFMPEG_PATH environment variable and uses npm to start the web application. This is useful for developers testing changes on their macOS machines. ```bash cd video-bot && FFMPEG_PATH=/opt/homebrew/bin/ffmpeg npm run start:web ``` -------------------------------- ### Local Bot Testing Command Source: https://github.com/atticdm/getsocialvideobot/blob/main/docs/CONTEXT.md This command shows how to build and run the Telegram bot locally. It involves navigating to the video-bot directory, building the TypeScript project, and then starting the bot application. ```bash cd video-bot && npm run build && npm start ``` -------------------------------- ### Inline Query Handler Setup (TypeScript) Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Configures the Telegram bot to handle inline queries, allowing users to share videos from social media in any chat by mentioning the bot and providing a URL. This involves downloading the video, potentially uploading it to a temporary server, and returning an inline video card for selection. ```typescript import { setupInlineHandlers } from './bot/inline'; import { Telegraf } from 'telegraf'; const bot = new Telegraf(process.env.BOT_TOKEN!); setupInlineHandlers(bot); // User types in any Telegram chat: // @getsocialvideobot https://www.instagram.com/reel/ABC123/ // The bot will: // 1. Download the video to a temporary directory // 2. Upload it to temp-server (if configured) or use local PUBLIC_URL // 3. Return an inline video card with thumbnail and playback // 4. When user selects the card, video is sent to the chat // 5. Clean up temporary files after delivery // Configuration required: process.env.TEMP_SERVER_URL = 'https://temp-video-server.onrender.com'; process.env.TEMP_SERVER_SECRET = 'your-secret-key'; // OR process.env.PUBLIC_URL = 'https://your-bot-domain.com'; ``` -------------------------------- ### Implement Rate Limiting with TypeScript Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Demonstrates how to use a rate limiter to control concurrent download requests for users. It shows how to check a user's current download status, acquire a slot before starting a download, and release the slot upon completion or error. This prevents overwhelming the system with too many simultaneous operations. ```typescript import { rateLimiter } from './core/rateLimit'; const userId = 12345678; // Check current user status const status = rateLimiter.getStatus(userId); console.log(status.active); // Number of active downloads console.log(status.total); // Total historical downloads // Enforce limit before starting download if (status.active >= 3) { await ctx.reply('⏸️ Too many downloads in progress. Please wait.'); return; } // Acquire slot (blocks until available) const release = await rateLimiter.acquire(userId); try { // Perform download operation await downloadVideo(url); } catch (error) { console.error('Download failed:', error); } finally { // Always release the slot release(); } ``` -------------------------------- ### Cookie-Based Authentication Configuration Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Guides on how to configure browser cookies for accessing private or restricted content. ```APIDOC ### Cookie-Based Authentication This section outlines the process for configuring browser cookies to enable the download of private or restricted content from various platforms. #### Steps: 1. **Export Cookies:** Use a browser extension to export cookies in a compatible format (e.g., Netscape format for Instagram). 2. **Encode Cookies:** Encode the exported cookie file into base64. ```bash # Example for Instagram: cat instagram_cookies.txt | base64 -w 0 > instagram_cookies_b64.txt ``` 3. **Set Environment Variables:** Set the base64 encoded cookies as environment variables for the relevant platform. ```bash export INSTAGRAM_COOKIES_B64=$(cat instagram_cookies_b64.txt) export FACEBOOK_COOKIES_B64=$(cat facebook_cookies.txt | base64 -w 0) export YOUTUBE_COOKIES_B64=$(cat youtube_cookies.txt | base64 -w 0) export TIKTOK_COOKIES_B64=$(cat tiktok_cookies.txt | base64 -w 0) export LINKEDIN_COOKIES_B64=$(cat linkedin_cookies.txt | base64 -w 0) export SORA_COOKIES_B64=$(cat sora_cookies.txt | base64 -w 0) ``` 4. **Optional Settings:** - **Skip Cookies:** To temporarily disable cookie usage: ```bash export SKIP_COOKIES=true ``` - **Debug Logging:** To enable debug logging for `yt-dlp`: ```bash export DEBUG_YTDLP=true ``` ``` -------------------------------- ### Get Video Metadata Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Retrieves metadata for a video using its URL. Caching is supported. ```APIDOC ## POST /get-video-link ### Description Retrieves metadata for a video, including download URL, title, duration, file size, and thumbnail. This endpoint utilizes caching for faster responses. ### Method POST ### Endpoint /get-video-link ### Parameters #### Request Body - **url** (string) - Required - The URL of the video. ### Request Example ```json { "url": "https://www.instagram.com/reel/ABC123/" } ``` ### Response #### Success Response (200) - **downloadUrl** (string) - The direct URL to download the video. - **title** (string) - The title of the video. - **duration** (number) - The duration of the video in seconds. - **fileSize** (integer) - The size of the video file in bytes. - **thumbnail** (string) - The URL of the video's thumbnail image. #### Response Example ```json { "downloadUrl": "https://scontent.cdninstagram.com/v1/...", "title": "Amazing video", "duration": 45.2, "fileSize": 8394752, "thumbnail": "https://scontent.cdninstagram.com/v1/.../thumb.jpg" } ``` ``` -------------------------------- ### Cookie-Based Authentication Setup Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Configures browser cookies for downloading private or restricted content by encoding them to base64 and setting them as environment variables. This is crucial for platforms like Instagram, Facebook, YouTube, TikTok, LinkedIn, and others. The 'SKIP_COOKIES' and 'DEBUG_YTDLP' variables can be used to control behavior. ```bash # Export cookies from your browser using extension (cookies.txt format) # For Instagram: login to instagram.com, export cookies as Netscape format # Encode cookies to base64 cat instagram_cookies.txt | base64 -w 0 > instagram_cookies_b64.txt # Set environment variable export INSTAGRAM_COOKIES_B64=$(cat instagram_cookies_b64.txt) # Same process for other platforms export FACEBOOK_COOKIES_B64=$(cat facebook_cookies.txt | base64 -w 0) export YOUTUBE_COOKIES_B64=$(cat youtube_cookies.txt | base64 -w 0) export TIKTOK_COOKIES_B64=$(cat tiktok_cookies.txt | base64 -w 0) export LINKEDIN_COOKIES_B64=$(cat linkedin_cookies.txt | base64 -w 0) export SORA_COOKIES_B64=$(cat sora_cookies.txt | base64 -w 0) # Skip cookies temporarily export SKIP_COOKIES=true # Enable debug logging for yt-dlp export DEBUG_YTDLP=true ``` -------------------------------- ### Configure Environment Variables with TypeScript Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Defines the complete environment variable configuration schema for the application, including app mode, bot settings, external tools paths, inline mode setup, caching parameters, platform cookies, debug options, and translation service keys. It uses TypeScript for type safety and provides default values for many configurations. ```typescript import { config } from './core/config'; // App mode config.APP_MODE // 'bot' | 'web' // Bot settings config.BOT_TOKEN // Required in bot mode config.DOWNLOAD_DIR // Default: './.tmp' config.MAX_FILE_MB // Default: 1950 // External tools config.FFMPEG_PATH // Default: 'ffmpeg' config.PYTHON_PATH // Default: 'python3' // Inline mode setup config.PUBLIC_URL // Public URL for webhook and inline videos config.TEMP_SERVER_URL // External temp server URL (Render, etc.) config.TEMP_SERVER_SECRET // Bearer token for temp server // Caching config.REDIS_URL // Redis connection string (optional) config.CACHE_PREFIX // Default: 'yeet:' config.CACHE_TTL_SECONDS // Default: 3600 // Platform cookies (base64-encoded) config.FACEBOOK_COOKIES_B64 config.INSTAGRAM_COOKIES_B64 config.LINKEDIN_COOKIES_B64 config.YOUTUBE_COOKIES_B64 config.TIKTOK_COOKIES_B64 config.SORA_COOKIES_B64 config.SKIP_COOKIES // Default: false // Debug and geo config.DEBUG_YTDLP // Default: false config.GEO_BYPASS_COUNTRY // Two-letter country code (e.g., 'US') // Translation services config.ENABLE_REEL_TRANSLATION // Default: true config.OPENAI_API_KEY config.OPENAI_WHISPER_MODEL // Default: 'whisper-1' config.OPENAI_TRANSLATE_MODEL // Default: 'gpt-4o-mini' config.HUME_API_KEY config.HUME_CLIENT_SECRET config.HUME_VOICE_ID_RU_MALE config.HUME_VOICE_ID_RU_FEMALE config.HUME_VOICE_ID_EN_MALE config.HUME_VOICE_ID_EN_FEMALE config.ELEVENLABS_API_KEY config.LALAL_API_KEY // Logging config.LOG_LEVEL // 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' ``` -------------------------------- ### Handle Errors with TypeScript Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Provides a structured error handling system using a custom `AppError` class and predefined error codes. It includes functionality to convert these errors into user-friendly messages. The example shows how to throw specific application errors and catch them to provide appropriate feedback to the user. ```typescript import { AppError, ERROR_CODES, toUserMessage } from './core/errors'; // Define application errors throw new AppError( ERROR_CODES.ERR_PRIVATE_OR_RESTRICTED, 'Video is private or requires login', { url, statusCode: 403 } ); // Available error codes: // ERR_PRIVATE_OR_RESTRICTED - Login required or private content // ERR_GEO_BLOCKED - Region-restricted video // ERR_UNSUPPORTED_URL - Platform not supported // ERR_FETCH_FAILED - Network or rate limit error // ERR_FILE_TOO_LARGE - Exceeds MAX_FILE_MB limit // ERR_FILE_NOT_FOUND - Downloaded file missing // ERR_INTERNAL - General internal error // Convert to user message try { await provider.download(url, sessionDir); } catch (error) { if (error instanceof AppError) { const message = toUserMessage(error); await ctx.reply(message); // "❌ This video is private or requires login" } else { await ctx.reply('❌ Unknown error occurred'); } } ``` -------------------------------- ### Get Video Metadata (Cached) Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Retrieves cached metadata for a video, including download URL, title, duration, file size, and thumbnail. It sends a POST request with the video URL in JSON format and uses 'jq' to parse the JSON response. Requires a local web service on port 3000. ```bash # Get video metadata (cached) curl -X POST http://localhost:3000/get-video-link \ -H 'Content-Type: application/json' \ -d '{"url":"https://www.instagram.com/reel/ABC123/"}' | jq ``` -------------------------------- ### Docker Build and Run Commands Source: https://github.com/atticdm/getsocialvideobot/blob/main/video-bot/README.md These Docker commands demonstrate how to build the application's Docker image and then run it as a detached container. It includes instructions for running both the bot and the web components, with volume mapping for logs. ```bash # Build image docker build -t video-bot . # Run bot docker run -d --name video-bot \ -e BOT_TOKEN=your_bot_token \ -v $(pwd)/logs:/app/logs \ video-bot # Run web docker run -d --name video-web -p 3000:3000 \ -e APP_MODE=web -e PORT=3000 \ video-bot ``` -------------------------------- ### PM2 Process Management Bash Commands Source: https://github.com/atticdm/getsocialvideobot/blob/main/video-bot/README.md These commands build the project and then use PM2 to manage the application process, providing features like process monitoring, auto-restarting, and log management for production deployments. ```bash npm run build pm2 start ecosystem.config.cjs ``` -------------------------------- ### yt-dlp Command Optimization for YouTube Source: https://github.com/atticdm/getsocialvideobot/blob/main/docs/CONTEXT.md This shows the core yt-dlp command-line arguments used for optimizing YouTube downloads. It includes codec prioritization, SponsorBlock integration to remove ads, a file size limit for safety, and options to embed metadata and thumbnails for richer files. ```bash --sponsorblock-remove all --max-filesize 2G --embed-metadata --embed-thumbnail ``` -------------------------------- ### TypeScript Bot Entry Point Source: https://github.com/atticdm/getsocialvideobot/blob/main/docs/CONTEXT.md This entry point file for the video bot written in TypeScript. It likely initializes the bot, sets up event handlers, and connects to the Telegram API using the Telegraf framework. ```typescript // video-bot/src/bot/index.ts // Placeholder for actual bot initialization code ``` -------------------------------- ### TypeScript Web Server Implementation Source: https://github.com/atticdm/getsocialvideobot/blob/main/docs/CONTEXT.md This file contains the implementation of the Fastify web server. It defines API endpoints, including an atomic download endpoint that streams files directly to the client, and legacy endpoints for compatibility. ```typescript // video-bot/src/web/server.ts // Placeholder for Fastify server setup and route definitions ``` -------------------------------- ### Build TypeScript Project Bash Command Source: https://github.com/atticdm/getsocialvideobot/blob/main/video-bot/README.md This command compiles the TypeScript code into JavaScript, preparing the project for execution in a development or production environment. ```bash npm run build ``` -------------------------------- ### Run TikTok Detection Tests Source: https://github.com/atticdm/getsocialvideobot/blob/main/docs/TIKTOK_INTEGRATION.md These bash commands detail how to build the video-bot project and then run the specific detection tests for TikTok URLs. This verifies that the provider correctly identifies TikTok URLs. ```bash cd video-bot npm run build node test-tiktok.js ``` -------------------------------- ### YouTube Download Strategy Configuration Source: https://github.com/atticdm/getsocialvideobot/blob/main/docs/CONTEXT.md This snippet details the optimized strategy for downloading YouTube videos, prioritizing H.264 codecs for faster remuxing and reduced CPU usage. It includes fallback options and a safety net for recoding when necessary. This configuration aims for performance and compatibility, ensuring MP4 output. ```text 1) H.264 Priority: `bestvideo[vcodec^=avc]+bestaudio` (fast remux, no recoding) 2) Fallback: `bestvideo*+bestaudio/best` (any codec + safety net recoding) 3) Safety Net: `--recode-video mp4` (only activates if needed) ``` -------------------------------- ### Viewing Log Files (Bash) Source: https://github.com/atticdm/getsocialvideobot/blob/main/video-bot/README.md Command to tail log files, allowing real-time monitoring of application activity and errors during troubleshooting. ```bash tail -f logs/app.log tail -f logs/error.log ``` -------------------------------- ### Temp Server Deployment Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Details on deploying a separate Node.js server for hosting temporary video files in production. ```APIDOC ### Temp Server Deployment This section describes a separate Node.js server designed for hosting temporary video files in production environments. #### Server Configuration (`temp-server/server.js`): ```javascript import express from 'express'; import path from 'path'; // Assuming path is imported import multer from 'multer'; // Assuming multer is imported for upload const app = express(); const PORT = process.env.PORT || 8080; const TMP_DIR = '/tmp'; const UPLOAD_SECRET = process.env.UPLOAD_SECRET || 'change-this-secret'; // Multer configuration for file uploads const upload = multer({ dest: TMP_DIR }); // Serve static files with proper video headers app.use('/tmp', express.static(TMP_DIR, { setHeaders: (res, filePath) => { const ext = path.extname(filePath).toLowerCase(); if (ext === '.mp4') res.setHeader('Content-Type', 'video/mp4'); res.setHeader('Accept-Ranges', 'bytes'); res.setHeader('Cache-Control', 'no-store'); } })); // Upload endpoint (protected by bearer token) app.post('/upload', upload.single('video'), (req, res) => { if (req.headers.authorization !== `Bearer ${UPLOAD_SECRET}`) { return res.status(401).json({ error: 'Unauthorized' }); } const fileName = path.basename(req.file.path); res.json({ success: true, fileName, fileUrl: `/tmp/${fileName}` }); }); // Health check endpoint app.get('/healthz', (_req, res) => { res.json({ status: 'ok', tmpDir: TMP_DIR }); }); app.listen(PORT, () => { console.log(`Temporary server running on port ${PORT}`) }); ``` #### Environment Variables: - **PORT:** The port the server listens on (defaults to 8080). - **UPLOAD_SECRET:** A secret key required for authenticating upload requests (defaults to 'change-this-secret'). ``` -------------------------------- ### YouTube Download Logic (TypeScript) Source: https://github.com/atticdm/getsocialvideobot/blob/main/docs/CONTEXT.md This TypeScript file contains the core logic for downloading videos from YouTube. It implements the optimized download strategy, handling codec priorities, fallbacks, and safety nets for efficient video retrieval. ```typescript // video-bot/src/providers/youtube/download.ts // Placeholder for YouTube download implementation ``` -------------------------------- ### Base64 Encoding Cookies for Facebook Source: https://github.com/atticdm/getsocialvideobot/blob/main/video-bot/README.md This command demonstrates how to base64 encode a `cookies.txt` file, which can then be used as the `FACEBOOK_COOKIES_B64` environment variable to authenticate with Facebook if videos require login. ```bash # 1. Export cookies from your browser to cookies.txt (Netscape format) # 2. Base64-encode the file: base64 -w0 cookies.txt # 3. Set the value as FACEBOOK_COOKIES_B64 in your deploy platform ``` -------------------------------- ### Video Download Command (TypeScript) Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Handles the '/download' command to fetch videos from supported social media platforms. It detects the provider, uses yt-dlp for downloading, enforces file size limits, and sends the video to the user. Temporary files are automatically cleaned up. ```typescript import { Telegraf } from 'telegraf'; import { downloadCommand } from './bot/commands/download'; const bot = new Telegraf(process.env.BOT_TOKEN!); bot.command('download', downloadCommand); // Usage in Telegram: // /download https://www.instagram.com/reel/ABC123/ // /dl https://www.youtube.com/watch?v=dQw4w9WgXcQ // /get https://www.tiktok.com/@user/video/1234567890 // The bot will: // 1. Detect the provider (instagram, youtube, tiktok, facebook, linkedin, sora) // 2. Download the video using yt-dlp with platform-specific configurations // 3. Check file size (max 1950 MB by default) // 4. Send the video file back to the user // 5. Clean up temporary files automatically ``` -------------------------------- ### Download Video (Web) Source: https://github.com/atticdm/getsocialvideobot/blob/main/docs/DEBUG_PLAYBOOK.md Initiates the download, streaming, and cleanup of a video within a single request. ```APIDOC ## GET /download_video ### Description This endpoint downloads a video, sets the necessary headers, streams the content, and performs cleanup within a single HTTP request. ### Method GET ### Endpoint /download_video ### Parameters #### Query Parameters - **url** (string) - Required - The URL of the video to download. This URL should be URL-encoded. ### Request Example ```json { "example": "GET /download_video?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdQw4w9WgXcQ" } ``` ### Response #### Success Response (200) - The response will be the streamed video content. #### Response Example (Binary stream of the video file) ``` -------------------------------- ### LALAL.AI Audio Separation Integration Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Documentation for integrating LALAL.AI to separate vocals and instrumental tracks from audio files. ```APIDOC ### LALAL.AI Audio Separation This service separates vocals and instrumental tracks from audio files, enabling remixing and audio processing workflows. #### Usage: 1. **Import Function:** ```typescript import { separateAudioWithLalal } from './services/lalal'; ``` 2. **Call Function:** ```typescript const audioPath = '/tmp/mixed_audio.mp3'; const result = await separateAudioWithLalal(audioPath); console.log(result.vocalPath); // '/tmp/mixed_audio.lalal.vocals.mp3' console.log(result.instrumentalPath); // '/tmp/mixed_audio.lalal.instrumental.mp3' ``` #### Service Workflow: - Uploads the audio file to LALAL.AI. - Triggers stem separation (vocals vs. instrumental). - Polls job status every 5 seconds (up to 60 attempts). - Downloads both separated tracks. - Returns the local file paths for vocals and instrumentals. #### Configuration: - **LALAL_API_KEY:** Set your LALAL.AI API key as an environment variable. ```typescript process.env.LALAL_API_KEY = 'your-lalal-api-key'; ``` #### Error Handling: - The service includes detailed error logging, capturing status codes, API responses, and stack traces. ```typescript try { const tracks = await separateAudioWithLalal(audioPath); } catch (error) { console.error(error.message); } ``` ``` -------------------------------- ### ElevenLabs Dubbing Service Integration Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Details on integrating the ElevenLabs service for AI-powered video dubbing and voice cloning. ```APIDOC ### ElevenLabs Dubbing Service This service provides high-quality AI dubbing for video translation, featuring voice cloning capabilities. #### Usage: 1. **Import Function:** ```typescript import { dubVideoWithElevenLabs } from './services/elevenlabs'; ``` 2. **Call Function:** ```typescript const sourceAudioPath = '/tmp/original_audio.mp3'; const targetLanguage = 'ru'; // e.g., 'en', 'es', 'fr' const sourceLanguage = 'en'; // Optional, auto-detect if omitted const dubbedPath = await dubVideoWithElevenLabs( sourceAudioPath, targetLanguage, sourceLanguage ); // Returns: '/tmp/.elevenlabs/dubbed-abc123.mp3' ``` #### Service Workflow: - Uploads audio to the ElevenLabs API. - Polls for dubbing completion (up to 10 minutes). - Downloads the dubbed audio track. - Returns the local file path of the translated audio. - Preserves original speaker characteristics. #### Configuration: - **ELEVENLABS_API_KEY:** Set your ElevenLabs API key as an environment variable. ```typescript process.env.ELEVENLABS_API_KEY = 'your-api-key'; ``` ``` -------------------------------- ### Download Video via Web Interface Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Downloads a video from a given URL using a local web service. Requires the web service to be running on localhost:3000. Outputs the downloaded video to a file named 'video.mp4'. ```bash curl 'http://localhost:3000/download_video?url=https://www.instagram.com/reel/ABC123/' \ -o video.mp4 ``` -------------------------------- ### Command Execution Utility (TypeScript) Source: https://github.com/atticdm/getsocialvideobot/blob/main/docs/CONTEXT.md This utility file provides functions for executing shell commands, likely used to interact with external tools like yt-dlp and ffmpeg. It handles process management, input/output streams, and error handling. ```typescript // video-bot/src/core/exec.ts // Placeholder for command execution utility ``` -------------------------------- ### Download Video Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Initiates a download for a video from a given URL and saves it to a file. ```APIDOC ## GET /download_video ### Description Downloads a video from the provided URL and saves it to a local file named 'video.mp4'. ### Method GET ### Endpoint /download_video ### Parameters #### Query Parameters - **url** (string) - Required - The URL of the video to download. ### Request Example ```bash curl 'http://localhost:3000/download_video?url=https://www.instagram.com/reel/ABC123/' \ -o video.mp4 ``` ### Response #### Success Response (200) - The response is the raw video data, saved to 'video.mp4'. #### Response Example (Binary video data saved to file) ``` -------------------------------- ### LALAL.AI Audio Separation Service Integration Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Utilizes the LALAL.AI service to separate vocals and instrumental tracks from an audio file. It uploads the audio, triggers stem separation, polls for job completion (up to 60 attempts), downloads both tracks, and returns their local file paths. Requires the LALAL_API_KEY to be set and includes error handling. ```typescript import { separateAudioWithLalal } from './services/lalal'; const audioPath = '/tmp/mixed_audio.mp3'; const result = await separateAudioWithLalal(audioPath); console.log(result.vocalPath); // '/tmp/mixed_audio.lalal.vocals.mp3' console.log(result.instrumentalPath); // '/tmp/mixed_audio.lalal.instrumental.mp3' // The service: // 1. Uploads audio file to LALAL.AI // 2. Triggers stem separation (vocals vs instrumental) // 3. Polls job status every 5 seconds (max 60 attempts) // 4. Downloads both separated tracks // 5. Returns local file paths // Configuration required: process.env.LALAL_API_KEY = 'your-lalal-api-key'; // Error handling with detailed logging try { const tracks = await separateAudioWithLalal(audioPath); } catch (error) { // Errors include status codes, API responses, and stack traces console.error(error.message); } ``` -------------------------------- ### Translation Workflow for Reels (TypeScript) Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Facilitates the translation of video audio between languages, including voice synthesis with emotional matching. It takes a video URL, session directory, and translation options, providing progress updates and returning the final translated video path, text, and audio path. ```typescript import { translateInstagramReel, ReelTranslationOptions } from './workflows/reelTranslate'; const options: ReelTranslationOptions = { direction: 'en-ru', // or 'ru-en' or 'auto' engine: 'hume' // or 'elevenlabs' for higher quality }; const sessionDir = '/tmp/session-123'; const instagramUrl = 'https://www.instagram.com/reel/ABC123/'; const result = await translateInstagramReel( instagramUrl, sessionDir, options, async (stage) => { // Progress callback for UI updates console.log(`Stage: ${stage.name}, Started: ${stage.startedAt}`); } ); // Result contains: // - videoPath: '/tmp/session-123/ABC123.final.mp4' // - translatedText: 'Translated script text' // - audioPath: '/tmp/session-123/final_audio.mp3' // - stages: [{ name: 'download', startedAt: 123, completedAt: 456 }, ...] ``` -------------------------------- ### Temporary Node.js Server Deployment Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Deploys a temporary Node.js server using Express for hosting video files in production environments. It serves static files from a '/tmp' directory with appropriate video headers, includes a protected upload endpoint using a bearer token, and a health check endpoint. The server port and upload secret are configurable via environment variables. ```javascript // temp-server/server.js import express from 'express'; const app = express(); const PORT = process.env.PORT || 8080; const TMP_DIR = '/tmp'; const UPLOAD_SECRET = process.env.UPLOAD_SECRET || 'change-this-secret'; // Serve static files with proper video headers app.use('/tmp', express.static(TMP_DIR, { setHeaders: (res, filePath) => { const ext = path.extname(filePath).toLowerCase(); if (ext === '.mp4') res.setHeader('Content-Type', 'video/mp4'); res.setHeader('Accept-Ranges', 'bytes'); res.setHeader('Cache-Control', 'no-store'); } })); // Upload endpoint (protected by bearer token) app.post('/upload', upload.single('video'), (req, res) => { if (req.headers.authorization !== `Bearer ${UPLOAD_SECRET}`) { return res.status(401).json({ error: 'Unauthorized' }); } const fileName = path.basename(req.file.path); res.json({ success: true, fileName, fileUrl: `/tmp/${fileName}` }); }); // Health check app.get('/healthz', (_req, res) => { res.json({ status: 'ok', tmpDir: TMP_DIR }); }); app.listen(PORT); ``` -------------------------------- ### Provider Detection and Video Download (TypeScript) Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Abstracts the process of identifying the social media provider from a URL and downloading video content. It allows fetching either the full video or just metadata like download URL, duration, and thumbnail, using provider-specific logic. ```typescript import { detectProvider, getProvider } from './providers'; const url = 'https://www.instagram.com/reel/ABC123/'; const providerName = detectProvider(url); // Returns: 'instagram' | 'facebook' | 'youtube' | 'tiktok' | 'linkedin' | 'sora' | null if (providerName) { const provider = getProvider(providerName); const sessionDir = '/tmp/download-session'; // Download video const result = await provider.download(url, sessionDir); console.log(result.filePath); // '/tmp/download-session/video-title.ABC123.mp4' console.log(result.videoInfo); // { id: 'ABC123', title: 'video-title', url: '...' } // Fetch metadata only (faster, no download) const metadata = await provider.metadata(url); console.log(metadata.downloadUrl); // Direct video URL console.log(metadata.duration); // Video duration in seconds console.log(metadata.thumbnail); // Thumbnail image URL } ``` -------------------------------- ### ElevenLabs AI Dubbing Service Integration Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Integrates with the ElevenLabs API for high-quality AI dubbing of video audio. It uploads the source audio, polls for dubbing completion (up to 10 minutes), downloads the dubbed track, and preserves original speaker characteristics. Requires the ELEVENLABS_API_KEY to be set. ```typescript import { dubVideoWithElevenLabs } from './services/elevenlabs'; const sourceAudioPath = '/tmp/original_audio.mp3'; const targetLanguage = 'ru'; // or 'en', 'es', 'fr', etc. const sourceLanguage = 'en'; // optional, auto-detect if omitted const dubbedPath = await dubVideoWithElevenLabs( sourceAudioPath, targetLanguage, sourceLanguage ); // Returns: '/tmp/.elevenlabs/dubbed-abc123.mp3' // The function: // 1. Uploads audio to ElevenLabs API // 2. Polls for dubbing completion (max 10 minutes) // 3. Downloads the dubbed audio track // 4. Returns path to the translated audio file // 5. Preserves original speaker characteristics // Configuration required: process.env.ELEVENLABS_API_KEY = 'your-api-key'; ``` -------------------------------- ### Implement Caching with TypeScript and Redis Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Implements a Redis-based caching layer using a `withCache` utility function. This function caches the results of expensive asynchronous operations, such as fetching video metadata. It uses a generated cache key and allows configuration of Redis connection details, cache prefix, and time-to-live (TTL). If Redis is unavailable, the operation proceeds without caching. ```typescript import { withCache } from './core/cache'; import { createHash } from 'crypto'; const cacheKey = `metadata:instagram:${createHash('sha1').update(url).digest('hex')}`; const metadata = await withCache(cacheKey, async () => { // Expensive operation: fetch metadata from yt-dlp const provider = getProvider('instagram'); return provider.metadata(url); }); // First call: executes function and caches result (TTL: 3600s) // Subsequent calls: returns cached result immediately // Cache configuration process.env.REDIS_URL = 'redis://localhost:6379'; process.env.CACHE_PREFIX = 'yeet:'; process.env.CACHE_TTL_SECONDS = '3600'; // If Redis is unavailable, function executes normally without caching ``` -------------------------------- ### Inline Video Proxy for Telegram Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Provides an inline video proxy suitable for Telegram's instant view feature. It streams video chunks by accepting a 'Range' header, allowing for efficient streaming of large video files. The service is expected to be running on localhost:3000. ```bash curl 'http://localhost:3000/iv.mp4?url=https://www.instagram.com/reel/ABC123/' \ -H 'Range: bytes=0-1048575' \ -o video-chunk.mp4 ``` -------------------------------- ### Inline Video Proxy Source: https://context7.com/atticdm/getsocialvideobot/llms.txt Provides a proxy for video streams, suitable for inline playback in applications like Telegram. ```APIDOC ## GET /iv.mp4 ### Description Acts as a proxy for video streams, enabling inline playback. It supports byte range requests for streaming. ### Method GET ### Endpoint /iv.mp4 ### Parameters #### Query Parameters - **url** (string) - Required - The URL of the video to proxy. #### Headers - **Range** (string) - Optional - Specifies the byte range for the video stream (e.g., 'bytes=0-1048575'). ### Request Example ```bash curl 'http://localhost:3000/iv.mp4?url=https://www.instagram.com/reel/ABC123/' \ -H 'Range: bytes=0-1048575' \ -o video-chunk.mp4 ``` ### Response #### Success Response (200 or 206 Partial Content) - The response is the video stream data. #### Response Example (Binary video stream data) ``` -------------------------------- ### Add TIKTOK_COOKIES_B64 to Railway Deployment Source: https://github.com/atticdm/getsocialvideobot/blob/main/docs/TIKTOK_INTEGRATION.md This illustrates how to configure the `TIKTOK_COOKIES_B64` environment variable for production deployment on Railway. This is optional but necessary for accessing certain types of restricted TikTok content. ```bash TIKTOK_COOKIES_B64= GEO_BYPASS_COUNTRY=US ``` -------------------------------- ### TikTok Detection Module Interface Source: https://github.com/atticdm/getsocialvideobot/blob/main/docs/TIKTOK_INTEGRATION.md This TypeScript code defines the interface for the TikTok URL detection module. It exports a single function `isTikTokUrl` that takes a URL string and returns a boolean indicating if it's a valid TikTok URL. ```typescript export function isTikTokUrl(url: string): boolean; ``` -------------------------------- ### Generate Base64 Encoded Cookies for TikTok Source: https://github.com/atticdm/getsocialvideobot/blob/main/docs/TIKTOK_INTEGRATION.md This snippet demonstrates how to generate a Base64 encoded string of Netscape formatted cookies for TikTok. This is required for accessing age-restricted, private, or region-locked content. The process involves exporting cookies from a browser and then encoding them using the `base64` command. ```bash # 1. Export cookies from your browser (Netscape format) # 2. Base64-encode the file base64 -w0 tiktok_cookies.txt # 3. Set in environment export TIKTOK_COOKIES_B64="" ``` -------------------------------- ### Set Geo-Bypass Country for TikTok Source: https://github.com/atticdm/getsocialvideobot/blob/main/docs/TIKTOK_INTEGRATION.md This bash script shows how to set the `GEO_BYPASS_COUNTRY` environment variable. This is used in conjunction with other settings to bypass geo-restrictions for TikTok content. The variable expects a two-letter country code. ```bash export GEO_BYPASS_COUNTRY=US ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.