Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Devtube Laravel Package

devswebdev/devtube

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install Dependencies:

    sudo apt install ffmpeg youtube-dl  # Linux (Ubuntu/Debian)
    

    For other OSes, ensure ffmpeg and youtube-dl are installed and accessible via CLI.

  2. Install Package:

    composer require devswebdev/devtube
    
  3. Publish Config:

    php artisan vendor:publish --provider="DevsWebDev\DevTube\DevTubeServiceProvider"
    

    Verify config/devtube.php and update bin_path to match your system’s youtube-dl location (check with which youtube-dl).

  4. First Use Case: Download a video from a URL and return it as a downloadable file:

    use DevsWebDev\DevTube\Download;
    
    $dl = new Download(
        url: "https://www.youtube.com/watch?v=example",
        format: "mp4",
        download_path: storage_path('app/videos')
    );
    $mediaInfo = $dl->download()->first();
    return response()->download($mediaInfo['file']->getPathname());
    

Implementation Patterns

Core Workflows

  1. Basic Download: Use the Download class to fetch and save media:

    $dl = new Download($url, $format, $downloadPath);
    $mediaInfo = $dl->download(); // Returns a collection of `MediaInfo` objects
    
    • $format: Supports formats like mp4, webm, or best (default).
    • $downloadPath: Directory to save files (default: storage_path('app/devtube')).
  2. Batch Processing: Loop through multiple URLs:

    $urls = ["url1", "url2"];
    foreach ($urls as $url) {
        $dl = new Download($url, "mp4");
        $dl->download();
    }
    
  3. Streaming Responses: Serve downloaded files directly without saving to disk:

    $dl = new Download($url, "mp4");
    $mediaInfo = $dl->download()->first();
    return response()->streamDownload(function () use ($mediaInfo) {
        echo file_get_contents($mediaInfo['file']->getPathname());
    });
    
  4. FFmpeg Conversion: Convert videos to audio (requires ffmpeg):

    $dl = new Download($url, "mp3"); // Auto-converts if supported
    $mediaInfo = $dl->download()->first();
    
  5. Custom Paths: Override default storage paths in config/devtube.php:

    'download_path' => storage_path('custom/videos'),
    'temp_path'     => sys_get_temp_dir(),
    
  6. Error Handling: Wrap downloads in try-catch to handle failures (e.g., invalid URLs, unsupported formats):

    try {
        $dl->download();
    } catch (\Exception $e) {
        Log::error("Download failed: " . $e->getMessage());
        return back()->with('error', 'Failed to download video.');
    }
    

Integration Tips

  • Queue Jobs: Offload downloads to a queue (e.g., Laravel Queues) for long-running tasks:

    Dispatch(new DownloadJob($url, $format));
    

    Implement DownloadJob with DevTube\Download logic.

  • Middleware: Restrict access to download endpoints:

    Route::middleware(['auth'])->group(function () {
        Route::get('/download', [YoutubeDownloadController::class, 'download']);
    });
    
  • Artisan Commands: Create a scheduled download task:

    php artisan make:command DownloadVideos
    

    Use DevTube\Download in the command to fetch videos periodically.

  • Testing: Mock DevTube\Download in unit tests:

    $mock = Mockery::mock(DevTube\Download::class);
    $mock->shouldReceive('download')->andReturn(collect([...]));
    

Gotchas and Tips

Pitfalls

  1. Dependency Conflicts:

    • Ensure youtube-dl and ffmpeg are up-to-date. Outdated versions may fail to fetch modern video formats.
    • Fix: Update dependencies manually or use a package manager like apt/brew.
  2. Path Permissions:

    • Laravel may lack write permissions for storage/app/devtube or custom paths.
    • Fix: Run chmod -R 775 storage/ or adjust config/devtube.php to use a writable directory.
  3. Unsupported URLs:

    • Not all URLs (e.g., private videos, age-restricted content) are downloadable.
    • Fix: Validate URLs before processing or handle exceptions gracefully.
  4. Memory Limits:

    • Large files may exceed PHP’s memory_limit.
    • Fix: Increase memory_limit in php.ini or stream files directly to the client.
  5. FFmpeg Missing:

    • If converting to mp3 or other formats, ensure ffmpeg is installed and in PATH.
    • Fix: Install ffmpeg or set a custom path in config/devtube.php:
      'ffmpeg_path' => '/usr/local/bin/ffmpeg',
      
  6. Rate Limiting:

    • Aggressive scraping may trigger anti-bot measures (e.g., YouTube bans).
    • Fix: Add delays between requests or use proxies.

Debugging Tips

  1. Log Output: Enable verbose logging in config/devtube.php:

    'verbose' => true,
    

    Check Laravel logs (storage/logs/laravel.log) for youtube-dl output.

  2. Manual Testing: Test youtube-dl commands directly in the terminal to isolate issues:

    youtube-dl --format mp4 "https://example.com"
    
  3. Check Returned Data: Inspect $mediaInfo for errors:

    dd($mediaInfo->first()['error']); // May contain `youtube-dl` output
    
  4. Environment-Specific Paths: Use absolute paths in config/devtube.php to avoid issues across environments:

    'bin_path' => '/full/path/to/youtube-dl',
    

Extension Points

  1. Custom Formats: Extend the package to support additional formats by modifying the Download class or creating a wrapper:

    $dl = new Download($url, "custom_format");
    $dl->setFfmpegArgs(['-vf', 'scale=640:480']); // Custom FFmpeg args
    
  2. Metadata Extraction: Parse MediaInfo objects to extract metadata (title, duration, etc.):

    $title = $mediaInfo['title'];
    $duration = $mediaInfo['duration'];
    
  3. Storage Adapters: Replace the default storage logic to use S3 or other cloud storage:

    $dl->setStorageAdapter(new S3Adapter());
    
  4. Event Listeners: Trigger events after download (e.g., notify users, update a database):

    event(new VideoDownloaded($mediaInfo));
    
  5. Configuration Overrides: Dynamically override settings per request:

    $dl->setOption('format', 'webm');
    $dl->setOption('path', $customPath);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
boundwize/pyrameter
testo/facade
headercat/phpstan-extension-ide-helper
yosymfony/parser-utils
innmind/black-box
babenkoivan/elastic-migrations
babenkoivan/elastic-adapter
sandermuller/package-boost-php
sandermuller/boost-core
depa/sulu-google-reviews-bundle
croct/plug-symfony
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk