Skip to content

Client Server API 2.0

cuhuak edited this page Jan 21, 2012 · 23 revisions

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 which initiate client and returns info 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, than it will be mounted as "drop box". If volume is not readable and not writable than 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 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 not always match 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 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 file paths is required to determinate on which files/directories to action.
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 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)
  • encrypt 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 type of 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 return 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
    "hash"   : "l0_SW1hZ2Vz",        // (String) hash of current file/dir path, first symbol must be letter, symbol before _underline_ - volume id 
    "phash"  : "l0Lw",               // (String) hash of parent directory
    "mime"   : "directory",          // (String) mime type
    "date"   : "30 Jan 2010 14:25",  // (String) last modification time (mtime)
    "size"   : 12345,                // (Number) file size in bytes
    "childs" : 1,                    // (Number) Only for directories. Marks if directory has child directories inside it. 0 - 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"
}

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 - add to return child directories (not a command but option? todo)
  • parents - add to return parent directories (not a command but option? todo)
  • ls - list files in directory (not a command but option? todo)
  • tmb - create thumbnails for selected files
  • size - return size for selected files
  • 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 more 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 selected files

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. Если == @true@, сообщает коннектору, что данный запрос - запрос инициализации и в возвращаемые данные будет включен массив @options@ и параметр @api@ (число или строка >= 2). Также этот параметр влияет на обработку параметра @target@ - хэш директории, содержимое, которой должно быть возвращено. Если @init == true@ и @target@ не установлен или такой директории не существует, то коннектор вернет данные для корневой директории тома по умолчанию. В противном случае - вернет ошибку "FIle not found".
  • target : (string), обязательный параметр. Хэш открываемой директории. Может быть не указан только если init == @true@
  • tree : (true|false), необязательный параметр. Если true, к возвращаемым данным будет добавлена информация о директориях всех томов начиная от корневых директорий на заданную в настройках тома глубину.

Answer:

  • api : (Number) Номер версии протокола, должно быть >= 2
  • cwd : (Object) Current Working Directory - Информация о текущей директории. Client-Server_Protocol_v2_RU#Информация-об-отдельном-файле
  • files : (Array) Массив объектов - файлов в текущей директории. Если аргумент tree == true, то добавляются папки из дерева директорий на заданную глубину. Порядок файлов роли не играет.
  • options : (Object) Дополнительная информация о текущем томе и директории
{
  options : {
    "path"          : "files/folder42",                                 // (String) Путь к текущей директории
    "url"           : "http://localhost/elfinder/files/folder42/",      // (String) URL текущей директории
    "tmbURL"        : "http://localhost/elfinder/files/folder42/.tmb/", // (String) URL директории с превью файлов изображений
    "separator"     : "/",                                              // (String) Разделитель пути для текущего тома
    "disabled"      : [],                                               // (Array)  Список команд, отключеных для этого тома
    "copyOverwrite" : 1,                                                // (Number) Разрешена или нет перезапись файлов с одинаковыми именами на текущем томе
    "archivers"     : {                                                 // (Object) Настройки архиваторов
      "create"  : [],                                                   // (Array)  Список mime типов архивов, которые могут быть созданы
      "extract" : []                                                    // (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) Библиотека для работы с изображениями
      }

    ]
  }
}

h3. file

Вывести файл в браузер. Аргументы:

  • cmd : file
  • target : hash файла,
  • download : Послать заголовок, чтобы браузер предложил сохранить файл на диск

Ответ: Содержимое файла будет ввыведено в браузер

h3. tree

Вернуть дочерние директории на заданную в опциях коннектора глубину Аргументы:

  • cmd : tree
  • target : hash родительской директории,

Ответ:

h3. parents

Вернуть все родительские директории и их прямых потомков. Аргументы:

  • cmd : parents
  • target : hash дочерней директории,

Ответ:

h3. ls

Вернуть список имен файлов в заданой директории. Аргументы:

  • cmd : ls
  • target : hash директории,

Ответ:

  • list : (Array) Список имен файлов

h3. mkdir

Создать новую директорию.

Аргументы:

  • cmd : mkdir
  • target : hash целевой директории,
  • name : имя новой директории

Ответ:

h3. mkfile

Создать новый пустой файл.

Аргументы:

  • cmd : mkfile
  • target : hash целевой директории,
  • name : имя нового файла

Ответ:

h3. rename

Переименование директории/файла

Аргументы:

  • cmd : rename
  • current : hash директории, где файл находится
  • target : hash директории/файла для переименования
  • name : новое имя директории/файла

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

h3. 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) "имя файла": "ошибка"
    }
}

h3. ping

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

Аргументы:

  • cmd : ping

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

h3. paste

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

Аргументы:

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

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

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

h3. rm

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

Аргументы:

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

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

h3. duplicate

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

Аргументы:

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

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

h3. read

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

Аргументы:

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

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


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

h3. 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
    }
}

h3. extract

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

Аргументы:

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

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

h3. archive

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

Аргументы:

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

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

h3. 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 если ещё остались картинки для которых не были созданы миниатюрки,
                 // иначе параметр отсутствует
}

h3. 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 то диалог изменения размера не будет работать корректно.

Clone this wiki locally