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

Synology Php Api Laravel Package

bytes-commerce/synology-php-api

Symfony bundle for the Synology NAS API (DSM). Quickly create an authenticated RequestManager and interact with shares and folders from your app. Requires PHP 8.2+ and Symfony 7.2+. Built on bytes-commerce/synology-php-api.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require bytes-commerce/synology-php-api
    

    No Symfony Flex? Manually register the bundle in config/bundles.php if using Symfony, or use the standalone package in Laravel.

  2. First Use Case: Upload a file to a Synology share:

    use BytesCommerce\SynologyApi\Factory\RequestManagerFactory;
    use BytesCommerce\SynologyApi\Client;
    
    $factory = new RequestManagerFactory();
    $manager = $factory->createManager(
        'https://your-nas.de99.quickconnect.to',
        'username',
        'password'
    );
    
    $client = new Client($manager);
    $client->uploadFile(
        '/path/to/local/file.txt',
        '/path/to/remote/share/folder/'
    );
    
  3. Where to Look First:

    • Package README for core methods.
    • Synology API Docs for endpoint specifics.
    • src/Client.php for available methods (e.g., listFiles, deleteFile, copyMoveItem).

Implementation Patterns

Usage Patterns

  1. Service Container Integration (Laravel): Bind the RequestManagerFactory and Client to Laravel’s container in AppServiceProvider:

    public function register()
    {
        $this->app->singleton(RequestManagerFactory::class, function ($app) {
            return new RequestManagerFactory();
        });
    
        $this->app->bind(Client::class, function ($app) {
            $factory = $app->make(RequestManagerFactory::class);
            return new Client($factory->createManager(
                config('synology.url'),
                config('synology.username'),
                config('synology.password')
            ));
        });
    }
    
  2. Configuration Management: Store credentials in .env:

    SYNOLOGY_URL=https://your-nas.de99.quickconnect.to
    SYNOLOGY_USERNAME=admin
    SYNOLOGY_PASSWORD=yourpassword
    

    Access via config('synology.*') or $_ENV.

  3. Common Workflows:

    • File Operations:
      // Upload
      $client->uploadFile('local.txt', '/remote/share/');
      
      // Download
      $client->downloadFile('/remote/share/file.txt', 'downloads/');
      
      // List files
      $files = $client->listFiles('/remote/share/');
      
    • Folder Management:
      // Create folder (recursively)
      $client->createFolder('/remote/share/new_folder/');
      
      // Delete file/folder
      $client->deleteFile('/remote/share/file.txt');
      
    • Copy/Move:
      $client->copyMoveItem(
          '/remote/share/source.txt',
          '/remote/share/destination.txt',
          'copy' // or 'move'
      );
      
  4. Error Handling: Wrap calls in try-catch blocks to handle Synology-specific errors:

    try {
        $client->uploadFile('file.txt', '/share/');
    } catch (\BytesCommerce\SynologyApi\Exception\SynologyException $e) {
        Log::error('Synology upload failed: ' . $e->getMessage());
        // Retry or notify admin
    }
    

Integration Tips

  1. Laravel Events: Trigger events for Synology operations (e.g., synology.file.uploaded):

    event(new SynologyFileUploaded($filePath, $remotePath));
    
  2. Queued Jobs: Offload long-running operations (e.g., large file transfers) to Laravel Queues:

    UploadToSynology::dispatch('large_file.zip', '/backup/')->onQueue('synology');
    
  3. Caching: Cache frequent API calls (e.g., listFiles) using Laravel Cache:

    $files = Cache::remember("synology_files_{$path}", now()->addHours(1), function () use ($client, $path) {
        return $client->listFiles($path);
    });
    
  4. Middleware: Add auth/validation middleware for Synology requests:

    $manager->getClient()->getEmitter()->on('request', function ($request) {
        $request->setHeader('X-Synology-Token', config('synology.token'));
    });
    

Gotchas and Tips

Pitfalls

  1. Authentication:

    • QuickConnect URLs: Ensure the NAS is accessible via QuickConnect (*.de99.quickconnect.to) or a static IP.
    • Token Expiry: Synology sessions may expire; implement token refresh logic if needed.
    • Password Changes: Store credentials securely (Laravel’s encryption or Hashicorp Vault).
  2. Path Handling:

    • Slashes: Synology APIs are sensitive to trailing slashes. Use rtrim() or DIRECTORY_SEPARATOR:
      $path = rtrim($path, '/') . '/';
      
    • Invalid Paths: The dest_folder_path parameter (introduced in 1.0.5) replaces dest_folder. Update old code:
      // Old (deprecated)
      $client->copyMoveItem('source', 'dest_folder', 'copy');
      
      // New
      $client->copyMoveItem('source', 'dest_folder_path/', 'copy');
      
  3. File Operations:

    • Overwrite Behavior: Rename operations (1.0.8) auto-delete existing files. Test in staging first.
    • Special Characters: Use json_encode() for paths with special chars (1.0.2):
      $path = json_encode('/share/folder with spaces/');
      
  4. Performance:

    • Timeouts: Add a timeout to the RequestManagerFactory (1.0.13):
      $manager = $factory->createManager($url, $user, $pass, 30); // 30s timeout
      
    • Large Files: Stream uploads/downloads to avoid memory issues:
      $client->uploadFile('large_file.iso', '/backup/', [
          'stream' => true,
          'chunk_size' => 1024 * 1024, // 1MB chunks
      ]);
      
  5. Caching:

    • Invalidation: Deletes (1.0.9) invalidate cache. Clear cache manually if needed:
      Cache::forget("synology_files_{$path}");
      

Debugging

  1. Enable Logging: Configure Guzzle logging to debug API calls:

    $manager->getClient()->getEmitter()->on('request', function ($request) {
        Log::debug('Synology Request:', [
            'url' => $request->getUri(),
            'method' => $request->getMethod(),
            'body' => $request->getBody(),
        ]);
    });
    
  2. Common Errors:

    • 401 Unauthorized: Verify credentials or QuickConnect URL.
    • 404 Not Found: Check if the share/folder exists on the NAS.
    • 500 Internal Server Error: Synology API may reject malformed paths or unsupported operations.
  3. Testing:

    • Use a test NAS or mock the Client for unit tests:
      $mockClient = Mockery::mock(Client::class);
      $mockClient->shouldReceive('uploadFile')->andReturn(true);
      

Extension Points

  1. Custom Requests: Extend the Client to add missing endpoints:

    class ExtendedSynologyClient extends Client
    {
        public function customEndpoint($data)
        {
            return $this->request('POST', '/api/custom', $data);
        }
    }
    
  2. Event Listeners: Listen for Synology events (e.g., file uploads) and trigger Laravel events:

    $client->getManager()->getEmitter()->on('uploaded', function ($event) {
        event(new SynologyFileUploaded($event->getFile()));
    });
    
  3. Retry Logic: Implement custom retry logic for transient failures:

    $client->withRetry(3, function ($exception) {
        return $exception instanceof \GuzzleHttp\Exception\ConnectException;
    });
    
  4. Async Operations: Use Laravel Queues for background processing:

    class UploadToSynology implements ShouldQueue
    {
        public function handle()
        {
            $client->uploadFile($this->localPath, $this->remotePath);
        }
    }
    
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.
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
anil/file-picker
broqit/fields-ai