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

Sonata Media Webcam Provider Bundle Laravel Package

anacona16/sonata-media-webcam-provider-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require anacona16/sonata-media-webcam-provider-bundle
    
    • Ensure sonata-project/media-bundle is installed (v3.0 or v4.0).
  2. Enable the Bundle

    • For Symfony Flex: Automatically enabled.
    • For manual setup, add to config/bundles.php:
      Anacona16\Bundle\SonataMediaWebcamProviderBundle\SonataMediaWebcamProviderBundle::class => ['all' => true],
      
  3. Install Assets

    php bin/console assets:install --symlink
    
  4. Add JavaScript to Layout Include in your base template (e.g., templates/base.html.twig):

    <script src="{{ asset('bundles/sonatamediawebcamprovider/sonata-media-webcam-provider.min.js') }}"></script>
    
  5. Configure SonataMediaBundle Update config/packages/sonata_media.yaml:

    sonata_media:
        contexts:
            default:
                providers:
                    - sonata.media.provider.webcam
    

First Use Case

  • Create a Media Type in SonataAdmin with webcam as the provider.
  • In the admin interface, the webcam capture button will appear in the media form.

Implementation Patterns

Workflow for Media Upload via Webcam

  1. Admin Form Integration

    • Extend a Sonata media type to use the webcam provider:
      # config/packages/sonata_media.yaml
      sonata_media:
          types:
              my_webcam_type:
                  provider: sonata.media.provider.webcam
                  formats: [small, medium, large]
      
    • The form will render a custom webcam capture button.
  2. Handling Captures

    • The JavaScript (sonata-media-webcam-provider.min.js) handles:
      • Webcam access permissions.
      • Image capture via <canvas>.
      • Base64 encoding and temporary file creation.
    • The captured image is processed by Sonata’s ImageProvider.
  3. Validation & Fallbacks

    • If the webcam fails, the form falls back to traditional file uploads.
    • Validate the captured image size/resolution in your media type’s validate() method:
      public function validate(MediaInterface $media)
      {
          if ($media->getProviderName() === 'sonata.media.provider.webcam') {
              $this->validateWebcamDimensions($media);
          }
      }
      
  4. Customizing the Webcam UI

    • Override the webcam template:
      {# templates/SonataMediaWebcamProvider/webcam.html.twig #}
      <button id="sonata-media-webcam-capture" class="btn btn-primary">
          {{ 'Capture from Webcam'|trans }}
      </button>
      
    • Extend JavaScript via data-sonata-media-webcam-options:
      <div data-sonata-media-webcam-options='{"width": 640, "height": 480}'>
          {# Webcam container #}
      </div>
      
  5. Programmatic Usage

    • Trigger webcam capture via JavaScript:
      $('#sonata-media-webcam-capture').click();
      
    • Listen for capture events:
      $(document).on('sonata.media.webcam.captured', function(e, data) {
          console.log('Captured image:', data.base64);
      });
      

Gotchas and Tips

Pitfalls

  1. Webcam Permissions

    • Browsers block webcam access unless triggered by a user action (e.g., button click).
    • Test in Chrome/Firefox (Safari has limited support). Avoid iframes for capture.
  2. Temporary File Handling

    • The bundle creates temporary files during capture. Ensure:
      • The sys_temp_dir in sonata_media.yaml is writable.
      • Cleanup is handled (Symfony’s Filesystem component manages this).
  3. Image Processing

    • Webcam images may not match expected formats (e.g., JPEG vs. PNG). Configure sonata_media formats:
      sonata_media:
          formats:
              small: { width: 100, quality: 70 } # Force JPEG
      
  4. Symfony 5+ Flex Compatibility

    • If using Symfony 5+, ensure assets:install is run post-install.
    • For production, use php bin/console assets:install --no-debug.
  5. Debugging Captures

    • Check browser console for errors (e.g., NotAllowedError for webcam access).
    • Log the base64 data to verify capture:
      console.log(event.detail.base64.substring(0, 100) + '...');
      

Tips

  1. Performance

    • Limit webcam resolution in JavaScript to reduce processing time:
      data-sonata-media-webcam-options='{"width": 800, "height": 600}'
      
  2. Fallback UX

    • Provide a clear message when webcam fails:
      {% if not app.request.isXmlHttpRequest %}
          <div class="alert alert-warning">
              {{ 'Webcam not available. Upload a file manually.'|trans }}
          </div>
      {% endif %}
      
  3. Testing

    • Mock webcam access in tests using sonata.media.provider.webcam events:
      $this->get('event_dispatcher')->dispatch(
          new MediaWebcamCapturedEvent($media, $base64Image)
      );
      
  4. Extending Functionality

    • Add filters to webcam images:
      sonata_media:
          providers:
              sonata.media.provider.webcam:
                  filters:
                      - sonata.media.filter.image
                      - app.custom_webcam_filter
      
    • Create a custom filter to auto-crop or apply effects.
  5. Security

    • Validate file types even for webcam captures (malicious base64 data is possible):
      use Symfony\Component\HttpFoundation\File\UploadedFile;
      $tempFile = tempnam(sys_get_temp_dir(), 'sonata_webcam_');
      file_put_contents($tempFile, base64_decode($base64Image));
      $uploadedFile = new UploadedFile($tempFile, 'webcam_capture.jpg');
      $this->validateFile($uploadedFile);
      
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope