Skip to content
This repository has been archived by the owner on Sep 29, 2020. It is now read-only.

Client Server API 2.0

Josh Schmidt edited this page Oct 30, 2012 · 1 revision

Client-Server API 2.0

API version: 2.0 (draft)

General description

Client - JavaScript application which works in client's browser.

Connector - application which works on server (server-side). Connector executes commands were initiated by the client and returns result to the client.

Volume - One of the root folders (can be just one or multiple). Each volume mounted using driver (class) which implements logic of data storage (local filesystem, remote filesystem, database, etc.). If volume is not available for reading, but available for writing, then it will be mounted as "drop box". If volume is neither readable nor writable, then it will not be mounted.

Default volume - First volume available for reading.

The initiator of the connection is always the client, there is no long polling between client and server.
Client and connector work over HTTP(S) protocol and use JSON format for data exchange.
Connector must always return correct header Content-Type: application/json, except for file and upload commands.
Client passes commands to connector using HTTP GET or POST methods.
Connector always expects cmd argument (name of the command) from client, example: http://localhost/connector.php?cmd=open.

Name of commands on the client side doesn't always match with the connector side:

  • client commands reload, back, forward, home - implemented in connector using open command
  • client command open calls connector's open command for directory and file command for a file (if URL option is missing in client options)
  • client command cut, copy, paste - implemented in connector using copy
  • client commands which change the look of file manager and displays detailed info do not require request to connector.

File paths (hashes)

For executing most of the commands, passing files path is required to determinate on which files/directories to act upon.
Paths are NEVER passed in clear text format. Passing paths in clear text format will lead to unwanted disclosure of information and can stop client side from working at all.
All paths between client and connector are passed in encrypted format called hash.

Old 1.0 API used MD5 for encryption - it made connector more complicated and caused problems with performance, so it's not recommended to use it anymore.

New 2.x PHP connector uses next algorithm to create hash from file path:

  • remove root path from file path
  • encrypt resulting path so it could be later decrypted (not implemented yet, but stub is present)
  • encode already encrypted path using base64 with replacement +/= -> -_.
  • remove trailing dots
  • add prefix - unique volume id (must start with [a-z])
  • resulting string must be valid HTML id attribute (that is why base64 is used).

Using this algorithm even without encryption, client cannot get real file paths on the server only relative to root paths. This hash algorithm is recommended but you can use your own implementation until it matches 2 rules: "resulting string must be valid HTML id attribute", "hash must be decryptable by connector".

Errors

In case of fatal error (unable to give client correct information), connector must return JSON answer with error key. error value can be of type string or array. Error messages are passed as keys, which will be translated by client. List of available keys can be found in /js/i18n/elfinder.en.js starting with err.

Examples:

{"error" : ["errConf", "errJSON"]} // "Invalid backend configuration. PHP JSON module not installed"
{"error" : "Invalid backend configuration"}
{"error" : ["errLocked", "Some_folder"]} // 'Folder "Some_folder" can’t be opened because you don’t have permission to see its contents.' 

In case if command not found return:

{"error" : "errUnknownCmd"} // "Unknown command"

If some required parameter is missing:

{"error" : ["errCmdParams", "command_name"]} // "Invalid parameters for command "command_name"."

Any other data send with error parameter will be ignored on client side.

Information about file/directory

In most cases connector returns information about files or directories. Info about each file/directory is represented as object with parameters, it is called object format. Example:

{
    "name"   : "Images",             // (String) name of file/dir. Required
    "hash"   : "l0_SW1hZ2Vz",        // (String) hash of current file/dir path, first symbol must be letter, symbols before _underline_ - volume id, Required. 
    "phash"  : "l0_Lw",               // (String) hash of parent directory. Required except roots dirs.
    "mime"   : "directory",          // (String) mime type. Required.
    "ts"     : 1334163643,           // (Number) file modification time in unix timestamp. Required.
    "date"   : "30 Jan 2010 14:25",  // (String) last modification time (mime). Depricated but yet supported. Use ts instead.
    "size"   : 12345,                // (Number) file size in bytes
    "childs" : 1,                    // (Number) Only for directories. Marks if directory has child directories inside it. 0 (or not set) - no, 1 - yes. Do not need to calculate amount.
    "read"   : 1,                    // (Number) is readable
    "write"  : 1,                    // (Number) is writable
    "locked" : 0,                    // (Number) is file locked. If locked that object cannot be deleted and renamed
    "tmb"    : 'bac0d45b625f8d4633435ffbd52ca495.png' // (String) Only for images. Thumbnail file name, if file do not have thumbnail yet, but it can be generated than it must have value "1"
    "alias"  : "files/images",       // (String) For symlinks only. Symlink target path.
    "thash"  : "l1_c2NhbnMy",        // (String) For symlinks only. Symlink target hash.
    "dim"    : "640x480"             // (String) For images - file dimensions. Optionally.
    "volumeid" : "l1_"               // (String) Volume id. For root dir only.
}

File manager initialization

Client sends request with open command, init parameter.

Example: http://localhost/connector.php?cmd=open&init=1

Command list

  • open - open directory
  • file - output file contents to the browser (download)
  • tree - return child directories
  • parents - return parent directories and its childs
  • ls - list files in directory
  • tmb - create thumbnails for selected files
  • size - return size for selected files or total folder(s) size
  • dim - return image dimensions
  • mkdir - create directory
  • mkfile - create text file
  • rm - delete file
  • rename - rename file
  • duplicate - create copy of file
  • paste - copy or move files
  • upload - upload file
  • get - return text file contents
  • put - save text file
  • archive - create archive
  • extract - extract archive
  • search - search for files
  • info - return info for files. (used by client "places" ui)
  • resize - modify image file (resize/crop/rotate)
  • netmount - mount network volume during user session. Only ftp now supports.

Command description

open

Returns information about requested directory and its content, option can return directory tree, and options of current volume.

Arguments:

  • init : (true|false|not set), optional parameter. If true indicates that this request is an initialization request and its response must include the array options and the value api (number or string >= 2). Also, this option affects the processing of parameter target hash value. If init == true and target is not set or that directory doesn't exist, then the data connector must return the root directory of the default volume. Otherwise it must return error "File not found".
  • target : (string) Hash of directory to open. Required if init == false or init is not set
  • tree : (true|false), optional. If true, response must contain subfolders trees of roots directories.

Answer:

  • api : (Number) The version number of the protocol, must be >= 2, ATTENTION - return api ONLY for init request!
  • cwd : (Object) Current Working Directory - information about the current directory. Client-Server_Protocol_v2_RU#Информация-об-отдельном-файле
  • files : (Array) array of objects - files in current directory. If parameter tree == true, then added to the folder of the directory tree to a given depth. The order of files is not important. Client-Server_Protocol_v2_RU#Информация-об-отдельном-файле
  • uplMaxSize : (String) Optionally. Allowed upload max size. For example "32M"
  • options : (Object) Дополнительная информация о текущем томе и директории
  • netDrivers : (Array) Network protocols list which can be mounted on the fly (using netmount command). Now only ftp supported.
{
  options : {
    "path"          : "files/folder42",                                 // (String) Current folder path
    "url"           : "http://localhost/elfinder/files/folder42/",      // (String) Current folder URL
    "tmbURL"        : "http://localhost/elfinder/files/folder42/.tmb/", // (String) Thumbnails folder URL
    "separator"     : "/",                                              // (String) Разделитель пути для текущего тома
    "disabled"      : [],                                               // (Array) List of commands not allowed (disabled) on this volume
    "copyOverwrite" : 1,                                                // (Number) Разрешена или нет перезапись файлов с одинаковыми именами на текущем томе
    "archivers"     : {                                                 // (Object) Настройки архиваторов
      "create"  : [
        0 : "application/x-tar",
        1 : "application/x-gzip"
      ],                                                   // (Array)  Список mime типов архивов, которые могут быть созданы
      "extract" : [
        0 : "application/x-tar",
        1 : "application/x-gzip"
      ]                                                    // (Array)  Список mime типов архивов, которые могут быть распакованы
    }
  }
}
  • debug : (Object) Отладочная информация, если указана соответствующая опция коннектора.
{
  "debug":{
    "connector":"php",                     // (String) Тип коннектора
    "phpver"   : "5.3.6",                  // (String) Версия php
    "time"     : 0.0749430656433,          // (Number) Время выполнения скрипта
    "memory"   : "3348Kb / 2507Kb / 128M", // (String) Используемая/пиковая/доступная память
    "volumes"  : [                         // (Array)  Отладка по томам
      {
        "id"         : "l1_",              // (String) ID тома
        "driver"     : "localfilesystem",  // (String) Тип драйвера (имя класса)
        "mimeDetect" : "internal",         // (String) Метод определения mime типов
        "imgLib"     : "gd"                // (String) Библиотека для работы с изображениями
      }

    ],
    "mountErrors" : [                      // (Array) List of errors for not mounted volumes
      0 : "Root folder has not read and write permissions."
    ]
  }
}

file

Output file into browser. Arguments:

  • cmd : file
  • target : file's hash,
  • download : Send headers to force download file instead of open it in browser.

tree

Return folder's subfolders on required (in connector options) deep. Arguments:

  • cmd : tree
  • target : folder's hash

Response:

parents

Return all parents folders and its subfolders on required (in connector options) deep. Arguments:

  • cmd : parents
  • target : folder's hash,

Response:

ls

Return a list of file names in the target directory. arguments:

  • cmd : ls
  • target : hash of directory,

Response:

  • list : (Array) Files list.

mkdir

Create a new directory.

arguments:

  • cmd : mkdir
  • target : hash of target directory,
  • name : New directory name

Response:

mkfile

Create a new blank file.

Arguments:

  • cmd : mkfile
  • target : hash of target directory,
  • name : New file name

Response:

rename

Renaming a directory/file

Arguemnts:

  • cmd : rename
  • current : hash of the directory where the file is located
  • target : hash directory/file renaming
  • name : New name of the directory/file

Response: Client-Server_Protocol_v2_RU#open (если переименовали директорию, то open возвращается с деревом директорий) и select - hash переименованной директории/файла

upload

Загрузка файлов

Аргументы (передаются методом POST):

  • cmd : upload
  • current : hash директории, в которую загружаем файлы
  • upload : массив файлов (upload[])

Ответ:

  1. Если ни одного файла не удалось загрузить, возвращаем только

{
    "error" : "Unable to upload files"
}
  1. Если хотя бы один файл был загружен, ответ Client-Server_Protocol_v2_RU#open и select. Если не были загружены не все файлы от выведутся сообщения об ошибках error и errorData:

{
    // open
    "select"    : [ "8d331825ebfbe1ddae14d314bf81a712" ], // (Array)  массив hash'ей путей загруженных файлов
    "error"     : "Some files was not uploaded",          // (String) если не все файлы были загружены
    "errorData" : {                                       // (Object) инф. о файлах, которые не удалось загрузить
        "some-file.exe" : "Not allowed file type"         // (String) "имя файла": "ошибка"
    }
}

ping

Служебная команда, необходима для исправления бага Safari при загрузке файлов http://www.webmasterworld.com/macintosh_webmaster/3300569.htm

Аргументы:

  • cmd : ping

Ответ: отсылает пустую страницу с заголовком @Connection: close@

paste

Копирует или перемещает директории/файлы

Аргументы:

  • cmd : paste
  • src : hash директории, из которой перемещаем/копируем файлы
  • dst : hash директории, в которую перемещаем/копируем файлы
  • targets : массив hash'ей копируемых директорий/файлов
  • cut : 1 если файлы перемещаются, аргумент отсутствует если файлы копируются

Ответ: Если копирование/перемещение прошло успешно, возвращает Client-Server_Protocol_v2_RU#open с деревом директорий, если нет, то к ответу добавляются сообдения об ошибках error и errorData

Внимание! Команда должна прекращать копирование при первой же ошибке. Не допускается перезапись файлов/директорий с одинаковыми именами.

rm

Удаление файлов и рекурсивное удаление директорий

Аргументы:

  • cmd : rm
  • current : hash директории, из которой удалем файлы
  • targets : массив hash'ей удаляемых директорий/файлов

Ответ: Client-Server_Protocol_v2_RU#open с деревом директорий, при ошибках error и errorData.

duplicate

Создает копию директории/файла. Имя копии формируется следующим образом: базовое_имя_файла copy+порядковый номер.расширение (если есть)

Аргументы:

  • cmd : duplicate
  • current : hash директории, в которой создаем дубликат
  • target : hash директории/файла, для которого создаем дубликат

Ответ: Client-Server_Protocol_v2_RU#open (если скопировали директорию, то open возвращается с деревом директорий), select - hash пути дубликата.

read

Возвращает содержимое текстового файла.

Аргументы:

  • cmd : read
  • current : hash директории, в которой читаем файл
  • target : hash файла

Ответ: content - содержимое текстового файла


{
    "content": "Hello world!" // (String) содержимое текстового фала 
}

edit

Сохраняет полученный текст в файл.

Аргументы (передаются методом POST):

  • cmd : edit
  • current : hash директории, в которой сохраняется файл
  • target : hash файла
  • content : новое содержимое файла

Ответ: file - объект, аналогичный описывающему файл в секции cdc команды Client-Server_Protocol_v2_RU#open


{
    "file" : {
        "name"  : "README.txt",
        "hash"  : "8d331825ebfbe1ddae14d314bf81a712",
        "url"   : "http://localhost:8001/~troex/git/elfinder/files/wiki/README.txt",
        "date"  : "Today 14:25",
        "mime"  : "text/plain",
        "size"  : 1171,
        "read"  : true,
        "write" : true,
        "rm"    : true
    }
}

extract

Распаковывает архив.

Аргументы:

  • cmd : extract
  • current : hash директории, в которой находится файл
  • target : hash файла архива

Ответ: Client-Server_Protocol_v2_RU#open с деревом директорий

archive

Упаковывает директории/файлы в архив.

Аргументы:

  • cmd : archive
  • type : mime-тип создаваемого архива
  • current : hash директории, в которой находятся добавляемые в архив директории/файлы
  • targets : массив хэшей директорий/файлов

Ответ: Client-Server_Protocol_v2_RU#open, select - hash нового архива

tmb

Фоновая команда. Создает миниатюрки для картинок, не имеющих их. Кол-во создаваемых за раз миниатюрок, указывается в Connector_Configuration_RU опцией tmbAtOnce. По умолчанию - 5.

Аргументы:

  • cmd : tmb
  • current : hash пути к директории, в которой создаем миниатюрки

Ответ:


{
    "current": "b4473c8c08d1d499ecd7112f3398f125", // (String) hash пути к директории, в которой были созданы миниатюрки
    "images" : {                                   // (Object)
        "a696323d7fd86513754004ba8bc12967":        // (String) hash пути файла
            "http://localhost:8001/~troex/git/elfinder/files/.tmb/a696323d7fd86513754004ba8bc12967.png"
                                                   // (String) URL миниатюрки
    }, 
    "tmb": true  // (Boolean) возвращает true если ещё остались картинки для которых не были созданы миниатюрки,
                 // иначе параметр отсутствует
}

resize

Изменение размера изображения.

Аргументы:

  • cmd : resize
  • current : hash директории, в которой находится файл
  • target : hash пути изображения
  • width : новая ширина изображения
  • height : новая высота изображения

Ответ: Client-Server_Protocol_v2_RU#open, select - hash пути изображения

Чтобы была возможность изменять размер изображения, в cdc записи файла должен быть указан параметр resize и dim. resize должен быть установлен в true и dim содержать строку с размерами высоты и ширины (пр. "600x400"). Если resize указан без dim то диалог изменения размера не будет работать корректно.

netmount

Mount network volume during user session.

Arguments:

  • protocol : network protocol. Now only ftp supports. Required.
  • host : host name. Required.
  • path : root folder path.
  • port : port.
  • user : user name. Required.
  • pass : password. Required.
  • alias : mount point name. For future usage. Now not used on client side.
  • options : additional options for driver. For future usage. Now not used on client side.