Seafile PHP SDK

This is a PHP package for accessing Seafile Web API.

German Web Application Developer Available for Hire!

No marketing skills whatsoever, but low rates, nearly 20 years of experience, and german work attitude.

Get in touch now: https://sdo.sh/DevOps/#contact

Build StatusTest CoverageLicense

What is Seafile?

  • Open Source Cloud Storage for your teams and organizations
  • Built in File Encryption, better Protecting your Privacy
  • Collaboration around Files, file locking and other features make collaboration easy.

    How to get Started

To get started with Seafile PHP SDK, you may either set up your own private Seafile server (see https://www.seafile.com/en/product/private_server/) or obtain seacloud.cc accounthttps://seacloud.cc. Because the SDK is in its infancy it's highly recommended to set up a test server or create a test account.

It's not advisable yet to use your real server/account if you already got one.

After you have created your test account continue to the next step.

Roadmap and notes on development

Please note that this SDK currently is under active development and that things might change rather drastically.

If you are looking for stability please refer to stable tags.

The next stable version is planned for January 2018.

Obtain API token

Have a look at script bin/obtain_api_token.sh and use it if you feel comfortable with it. Basically, the script does this:

  1. mkdir ~/.seafile-php-sdk
  2. curl -d "username=you@example.com&password=123456" https://your.seafile-server.com/api2/auth-token/ > ~/.seafile-php-sdk/api-token.json

Insert your test user name and test user password. Hint: if user name contains a "+" char, replace the char with "%2B" (hex ascii for "+") or urlencode() the user name altogether. Just so you know.

The file ~/.seafile-php-sdk/api-token.json will look something like this:

  1. {"token": "your_api_token"}

The example script will assume a config file ~/.seafile-php-sdk/cfg.json that looks like this:

Have a look at script bin/create_test_cfg.sh and use it if you feel comfortable with it. Basically, the script does this:

  1. {
  2. "baseUri": "https://your-seafile-server.example.com",
  3. "testLibId": "test-library-id",
  4. "testLibPassword": "test-library-password"
  5. }

Installing Seafile-PHP-SDK

The recommended way to install seafile-php-sdk is throughComposer.

  1. # Install Composer
  2. curl -sS https://getcomposer.org/installer | php

Next, run the Composer command to install the latest stable version of seafile-php-sdk:

  1. composer.phar require rsd/seafile-php-sdk
  2. # composer.phar dump-autoload -o # not required anymore

After installing, you need to require Composer's autoloader:

  1. require 'vendor/autoload.php';

You can then later update seafile-php-sdk using composer:

  1. composer.phar update
  2. # composer.phar dump-autoload -o # not required anymore

Using Seafile PHP SDK

Hint: Have a look at bin/example.php — everything this SDK can do is covered there!

Connecting to Seafile

First, you need to include the API token (see above):

  1. $tokenFile = getenv("HOME") . "/.seafile-php-sdk/api-token.json";
  2.  
  3. $token = json_decode(file_get_contents($tokenFile));
  4.  
  5. $client = new Client(
  6. [
  7. 'base_uri' => 'https://your.seafile-server.com',
  8. 'debug' => false,
  9. 'headers' => [
  10. 'Authorization' => 'Token ' . $token->token
  11. ]
  12. ]
  13. );

List available libraries

  1. $libraryResource = new Library($client);
  2. $libs = $libraryResource->getAll();
  3.  
  4. foreach ($libs as $lib) {
  5. printf("Name: %s, ID: %s, is encrypted: %s\n", $lib->name, $lib->id, $lib->encrypted ? 'YES' : 'NO');
  6. }

List directory contents

  1. $directoryResource = new Directory($client);
  2. $lib = $libraryResource->getById('some library ID of yours');
  3. $items = $directoryResource->getAll($lib, '/'); // 2nd param is the name of the directory or '/'
  4.  
  5. foreach ($items as $item) {
  6. printf("%s: %s (%d bytes)\n", $item->type, $item->name, $item->size);
  7. }

Check if directory item exists

  1. $parentDir = '/'; // DirectoryItem must exist within this directory
  2. $directory = 'DirectoryName';
  3. if($directoryResource->exists($lib, $directoryItemName, $parentDir) === false) {
  4. // directory item does not exist
  5. }

Be aware that because Seafile Web API does not provide a function to do this check on its own, all items of the directory will get loaded for iteration. So that's not very efficient.

Create directory

  1. $parentDir = '/'; // Create directory within this folder
  2. $directory = 'DirectoryName'; // name of the new Directory
  3. $recursive = false; // recursive will create parentDir if not already existing
  4. $success = $directoryResource->create($lib, $directory, $parentDir, $recursive);

Download file from unencrypted library

  1. $dir = '/'; // dir in the library
  2. $saveTo = '/tmp/'. $item->name; // save file to this local path
  3. $fileResource = new File($client);
  4. $downloadResponse = $fileResource->downloadFromDir($lib, $item, $saveTo, $dir);

Download file from encrypted library

Trying to download a file from an encrypted library without unlocking it first wouldinevitably fail, so just unlock (API docs say "decrypt") the library before attempting:

  1. $success = $libraryResource->decrypt($libId, ['query' => ['password' => $password]]);
  2. // rest is the same as 'Download file from unencrypted library', see above

Upload file

  1.  
  2. $fileToUpload = '/path/to/file/to/be/uploaded.zip';
  3. $dir = '/'; // directory in the library to save the file in
  4. $response = $fileResource->upload($lib, $fileToUpload, $dir);
  5. $uploadedFileId = json_decode((string)$response->getBody());

Update file

  1. $response = $fileResource->update($lib, $newFilename, '/');
  2. $updatedFileId = json_decode((string)$response->getBody());

Get file details

  1. $directoryItem = $fileResource->getFileDetail($lib, '/' . basename($fullFilePath));

Get API user account info

  1. $accountResource = new Account($client);
  2.  
  3. $accountType = $accountResource->getInfo();
  4.  
  5. print_r($accountType->toArray());

Get all accounts

  1. $accountResource = new Account($client);
  2.  
  3. $accountTypes = $accountResource->getAll();
  4.  
  5. foreach ($accountTypes as $accountType) {
  6. print_r($accountType->toArray());
  7. }

Create account

  1. $newAccountType = (new AccountType)->fromArray([
  2. 'email' => 'someone@example.com',
  3. 'password' => 'password',
  4. 'name' => 'Hugh Jazz',
  5. 'note' => 'I will not waste chalk',
  6. 'institution' => 'Duff Beer Inc.'
  7. ]);
  8.  
  9. $success = $accountResource->create($newAccountType);

Update account

  1. $updateAccountType = (new AccountType)->fromArray([
  2. 'name' => 'Divine Hugh Jazz',
  3. 'email' => 'someone@example.com'
  4. ]);
  5.  
  6. $success = $accountResource->update($updateAccountType);

Get account info by email address

  1. $accountResource = new Account($client);
  2.  
  3. $accountType = $accountResource->getByEmail('someone@example.com');
  4.  
  5. print_r($accountType->toArray());

Delete account

  1. $accountResource = new Account($client);
  2.  
  3. $accountType = (new AccountType)->fromArray([
  4. 'email' => 'someone@example.com'
  5. ]);
  6.  
  7. $success = $accountResource->remove($accountType);

or

  1. $accountResource = new Account($client);
  2.  
  3. $success = $accountResource->removeByEmail('someone@example.com');

Get avatar of an account

  1. $accountType = (new AccountType)->fromArray([
  2. 'email' => 'someone@example.com'
  3. ]);
  4.  
  5. $avatarResource = new Avatar($client);
  6.  
  7. print_r($avatarResource->getUserAvatar($accountType)->toArray());

or

  1. print_r($avatarResource->getUserAvatarByEmail('someone@example.com')->toArray());
  1. $libraryResource = new Library($client);
  2. $directoryResource = new Directory($client);
  3. $fileResource = new File($client);
  4. $sharedLinkResource = new SharedLink($client);
  5.  
  6. // create share link for a file
  7. $expire = 5;
  8. $shareType = SharedLinkType::SHARE_TYPE_DOWNLOAD;
  9. $p = "/" . basename($newFilename);
  10. $password = 'qwertz123';
  11.  
  12. $shareLinkType = $sharedLinkResource->create($lib, $p, $expire, $shareType, $password);
  13.  
  14. // remove shared link
  15. $success = $sharedLinkResource->remove($shareLinkType);

Get all starred files, star and unstar file

  1. $libraryResource = new Library($client);
  2. $starredFileResource = new StarredFile($client);
  3.  
  4. // get all starred files
  5. $dirItems = $starredFileResource->getAll();
  6.  
  7. // unstar all starred files
  8. foreach ($dirItems as $dirItem) {
  9. $lib = $libraryResource->getById($dirItem->repo);
  10. $starredFileResource->unstar($lib, $dirItem);
  11. }
  12.  
  13. // re-star all files
  14. foreach ($dirItems as $dirItem) {
  15. $lib = $libraryResource->getById($dirItem->repo);
  16. $starredFileResource->star($lib, $dirItem);
  17. }

Debugging and how to enable logging of requests and responses

This example requires monolog. Log entries and Guzzle debug info will be written to stdout.

  1.  
  2. $logger = new Logger('Logger');
  3.  
  4. $stack = HandlerStack::create();
  5. $stack->push(
  6. Middleware::log(
  7. $logger,
  8. new MessageFormatter("{hostname} {req_header_Authorization} - {req_header_User-Agent} - [{date_common_log}] \"{method} {host}{target} HTTP/{version}\" {code} {res_header_Content-Length} req_body: {req_body} response_body: {res_body}")
  9. )
  10. );
  11.  
  12. $client = new Client(
  13. [
  14. 'base_uri' => 'https://your.seafile-server.com',
  15. 'debug' => true,
  16. 'handler' => $stack,
  17. 'headers' => [
  18. 'Authorization' => 'Token ' . $token->token
  19. ]
  20. ]
  21. );

Version history

Version 2.x (not yet released)

This version will not be backwards compatible with Version 1.x.

  • SEAF-001: Will support PHP >7.0.0 only. In case you require a version that still supports PHP 5.6 let _gth@sdo.sh">me know so I can tell you my rates :)
  • SEAF-002: Requires PHPUnit 6.x

    Version 1.0.1

Latest and last version to support PHP 5.6.

Issues

  • Please let me know of issues.

    Dependencies

  • PHP >=7.0 64 bits

  • Guzzle 6

    Seafile Web API V2 Support Matrix

Resource Support grade
Account ???⚪️
Starred Files ????
Group ?⚪️⚪️⚪️
File Share Link ??⚪️⚪️
Library/Library ??⚪️⚪️
Library/File ??⚪️⚪️
Library/Directory ??⚪️⚪️
Library/Multiple Files ????
Avatar ????
Events Yet to be done, _gth@sdo.sh">contact me
Organization Yet to be done, _gth@sdo.sh">contact me

Seafile Web API V2.1 Support Matrix

Resource Support grade
Web API v2.1 Yet to be done, _gth@sdo.sh">contact me

Seafile server compatibility

Tested with:

  • Seafile Server 5.1.3 for generic Linux/Debian Jessie
  • Seafile Server 5.1.3 for generic Linux/Debian Wheezy
  • Seafile Server 5.1.4 for generic Linux/Ubuntu Xenial
  • Seafile Server 6.0.3 for generic Linux/Ubuntu Xenial
  • Seafile Server 6.2.x for generic Linux/Ubuntu Xenial
  • If you require a backport for an older Seafile server version _gth@sdo.sh">contact me for a quote!

    Contributing

Please note that this package still is in its infancy. Only a part of the API has been implemented so far.

Pull requests are welcome. Please adhere to some very basic and simple principles:

MIT © 2015-2017 Rene Schmidt DevOps UG (haftungsbeschränkt) & Co. KG

原文: https://github.com/rene-s/Seafile-PHP-SDK