CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-tiktok-src

A tool for downloading TikTok videos with or without watermarks and automatically uploading them to Facebook Reels

Pending
Overview
Eval results
Files

video-processing.mddocs/

Video Processing

File management, format conversion, metadata handling, and download queue management utilities. Provides comprehensive video processing capabilities including quality selection, batch processing, and automated workflows.

Capabilities

Video Quality Selection

Interactive quality selection for TikTok videos with multiple resolution options.

/**
 * Interactive video quality selection via command line
 * @param videos - Array of available video quality options
 * @returns Selected video quality object
 */
function chooseVideoQuality(videos: VideoQuality[]): VideoQuality;

interface VideoQuality {
  /** Quality descriptor (e.g., "HD", "720p") */
  quality?: string;
  /** Video download URL */
  url: string;
}

Usage Examples:

These functions are part of the main application workflow when running node index.js. They are not exported for direct import but are used internally:

// When running the main application (node index.js)
// The user is presented with quality options automatically:
// Available video qualities:
// 1. HD
// 2. SD  
// 3. Mobile
// Choose video quality (enter number): 1

// The function handles user input and returns selected quality
// Includes fallback for empty/invalid video arrays
if (!videos || videos.length === 0) {
  console.log('No video qualities available. Using default.');
  return videos[0];
}

Metadata Management

Save and manage video metadata in JSON format for archival and reference.

/**
 * Save video metadata to JSON file
 * @param metadata - Video metadata object to save
 * @param filePath - Target file path for JSON output
 */
function saveMetadata(metadata: object, filePath: string): void;

Usage Examples:

This function is used internally by the main application during the download process:

// During the downloadAndUpload workflow, metadata is automatically saved:
// Save metadata (happens automatically in main app)
const videoMetadata = result.result; // TikTok API result
saveMetadata(videoMetadata, path.resolve('download', `${namafile}_metadata.json`));
// Creates: ./download/video123_metadata.json

Video Format Conversion

Convert videos between different formats using FFmpeg integration.

/**
 * Convert video to different format using FFmpeg
 * @param inputPath - Source video file path
 * @param outputPath - Target output file path  
 * @param format - Target video format (e.g., 'webm', 'avi', 'mov')
 * @returns Promise resolving when conversion completes
 */
function convertVideo(inputPath: string, outputPath: string, format: string): Promise<void>;

Usage Examples:

Video conversion happens automatically in the main application workflow:

// Conversion occurs automatically after download in the main app:
// Convert video (example to webm format) - from index.js
const webmPath = path.resolve('download', `${namafile}.webm`);
try {
  await convertVideo(downloadPath, webmPath, 'webm');
  console.log(`Video converted to WebM: ${webmPath}`);
} catch (error) {
  console.log(`Error converting video: ${error.message}`);
}

Complete Download and Upload Workflow

Integrated workflow combining download, processing, and upload operations.

/**
 * Complete integrated workflow: download TikTok video, process, and upload to Facebook
 * Includes quality selection, metadata saving, format conversion, and error handling
 * @param url - TikTok video URL to process
 * @param retries - Number of retry attempts on failure (default: 3)
 * @returns Promise resolving when workflow completes successfully
 * @throws Logs errors but doesn't throw, handles retries internally
 */
async function downloadAndUpload(url: string, retries?: number): Promise<void>;

/**
 * Interactive command-line interface functions
 * These functions handle user input and CLI workflow
 */
interface CLIFunctions {
  /** Prompt user to choose between single URL or list processing */
  promptForInputMode(): 'single' | 'list';
  /** Get single TikTok URL from user input */
  promptForSingleUrl(): string;
  /** Get file path containing URL list from user input */
  promptForListFilePath(): string;
}

Usage Examples:

This function is the core workflow of the main application:

// Called internally by the queue system and main application
// When user provides URL via CLI or when processing queue items:
await downloadAndUpload(url, retries);

// The function automatically:
// 1. Downloads video metadata and file  
// 2. Saves metadata to JSON
// 3. Converts video format
// 4. Uploads to Facebook Reels
// 5. Handles errors with retries

Batch URL Processing

Process multiple TikTok URLs from a text file with queue management.

/**
 * Process multiple URLs from a text file
 * @param filePath - Path to file containing URLs (one per line)
 */
function processUrlList(filePath: string): void;

Usage Examples:

This function is used when the user chooses "list" mode in the main application:

// When user runs: node index.js
// And selects "list" option, then provides file path
// The function reads urls.txt containing:
// https://vm.tiktok.com/ZSFxxxxxx/
// https://vm.tiktok.com/ZSFyyyyyy/
// https://vm.tiktok.com/ZSFzzzzzz/

// processUrlList('./urls.txt') is called internally
// Automatically adds all URLs to download queue

Download Queue Management

Concurrent download and upload processing with queue system.

/**
 * Better-queue instance for managing concurrent downloads
 */
const downloadQueue: Queue;

interface QueueTask {
  /** TikTok URL to process */
  url: string;
}

/**
 * Queue configuration options
 */
interface QueueConfig {
  /** Number of concurrent workers */
  concurrent: number;
}

// Queue events
downloadQueue.on('drain', () => void); // All tasks completed

Usage Examples:

import Queue from 'better-queue';

// Queue is pre-configured with concurrent: 2
const downloadQueue = new Queue(async (task, cb) => {
  await downloadAndUpload(task.url);
  cb(null, task);
}, { concurrent: 2 });

// Add single URL to queue
downloadQueue.push({ url: 'https://vm.tiktok.com/ZSFxxxxxx/' });

// Monitor queue completion
downloadQueue.on('drain', () => {
  console.log('All downloads completed!');
});

// Add multiple URLs
const urls = [
  'https://vm.tiktok.com/ZSFxxxxxx/',
  'https://vm.tiktok.com/ZSFyyyyyy/'
];
urls.forEach(url => downloadQueue.push({ url }));

File System Organization

Directory Structure

The video processing system organizes files in a structured manner:

project-root/
├── download/                 # Main download directory
│   ├── {videoId}.mp4        # Downloaded video files
│   ├── {videoId}_metadata.json  # Video metadata
│   └── {videoId}.webm       # Converted video files
├── cookies.json             # Facebook session cookies
└── config.json              # Bot configuration

File Naming Conventions

// File naming patterns
const patterns = {
  /** Original downloaded video */
  video: `{videoId}.mp4`,
  /** Video metadata */
  metadata: `{videoId}_metadata.json`, 
  /** Converted video */
  converted: `{videoId}.{format}`
};

Download Progress Tracking

Visual progress indicators for download operations using the progress package:

// Progress bar configuration
const progressBarOptions = {
  width: 40,
  complete: '<',
  incomplete: '•',
  renderThrottle: 1,
  format: `[ Downloading ] [:bar] :percent in :elapseds`
};

Error Handling and Retry Logic

Comprehensive error handling with automatic retry mechanisms:

Retry Configuration:

  • Default retry attempts: 3
  • Exponential backoff for network errors
  • Graceful degradation for missing data

Common Error Scenarios:

  1. Network Connectivity Issues:

    • TikTok API timeouts or rate limiting
    • Axios download failures
    • Puppeteer browser connection issues
  2. Invalid TikTok URLs:

    • URLs that don't match expected formats
    • Deleted or private videos
    • Regional restrictions
  3. Missing Video Data:

    • Empty response from TikTok API
    • No video qualities available
    • Corrupted API response
  4. Facebook Upload Failures:

    • Invalid session cookies
    • Videos exceeding 90-second limit
    • Facebook UI changes breaking selectors
    • Network issues during upload
  5. File System Errors:

    • Insufficient disk space
    • Permission issues in download directory
    • File already exists conflicts
  6. Video Processing Errors:

    • FFmpeg conversion failures
    • Unsupported video formats
    • Corrupted video files
  7. Queue System Errors:

    • Memory issues with large queues
    • Concurrent processing limits
    • Task callback errors

Error Recovery:

// Automatic retry with decreasing attempts
if (retries > 0) {
  console.log(`Error occurred. Retrying... (${retries} attempts left)`);
  await downloadAndUpload(url, retries - 1);
} else {
  console.log(`Failed to process URL after multiple attempts: ${url}`);
}

Install with Tessl CLI

npx tessl i tessl/npm-tiktok-src

docs

facebook-upload.md

index.md

telegram-bot.md

tiktok-api.md

video-processing.md

tile.json