Skip to content

Latest commit

 

History

History
163 lines (131 loc) · 7.41 KB

JSON_API.md

File metadata and controls

163 lines (131 loc) · 7.41 KB

Lua4RS with the RetroShare JSON API

The jsonapi Lua namespace works in the plugin and in the independent lua4rs-jsonapi runner. The runner needs Qt Core/Network and Lua 5.4 or 5.5; it does not link against RetroShare or require the plugin to be installed. This is an alternative to maintaining native C++ bindings for every API method.

Build the standalone runner

From an MSYS2 MinGW64 terminal with Qt 5.15 and Lua installed:

cd jsonapi-runner
qmake jsonapi-runner.pro
mingw32-make -j4

The Windows executable is release/lua4rs-jsonapi.exe. Run it in the same toolchain environment so the Qt and Lua DLLs can be found. On Linux use make; set LUA_PKGCONFIG=lua5.4 on the qmake command line if your distribution uses that pkg-config name. On Windows a custom Lua installation can be selected with qmake variables LUA_INCLUDEPATH and LUA_LIBS.

Connect

Enable the JSON API in your RetroShare build and authorize API credentials in RetroShare's JSON API settings. These are API credentials, not your profile password. Use the address and port configured there (default port: 9092).

For example, in PowerShell:

$env:RETROSHARE_API_URL = 'http://127.0.0.1:9092'
$env:RETROSHARE_API_USER = 'your-api-user'
$env:RETROSHARE_API_PASSWORD = 'your-api-password'
.\jsonapi-runner\release\lua4rs-jsonapi.exe .\scripts\jsonapi\jsonapi-friends.lua

Inside the plugin, start RetroShare with these environment variables or call:

assert(jsonapi.configure {
    url = "http://127.0.0.1:9092",
    username = os.getenv("RETROSHARE_API_USER"),
    password = os.getenv("RETROSHARE_API_PASSWORD"),
    timeout_ms = 10000
})

Configuration stays in memory per Lua state. Each configure replaces the previous configuration; omitted fields fall back to environment variables. RETROSHARE_API_TIMEOUT_MS supplies the default timeout (otherwise 10000 ms). Allowed timeouts are 1–120000 ms. Use loopback HTTP for a local server, or HTTPS with a trusted certificate for a remote server: HTTP Basic credentials are not encrypted by HTTP. Redirects are deliberately not followed.

Requests and JSON

local result, err, httpStatus = jsonapi.call("/rsPeers/getFriendList", {})
assert(result, err)
assert(result.retval, "RetroShare returned failure")
for _, id in ipairs(result.sslIds) do print(id) end

call POSTs a parameter table (default {}) or a JSON object string. Endpoint and parameter names must match the JSON API generated by your RetroShare build. It returns decodedResponse, nil, httpStatus, or nil, error, httpStatus. Status is zero if no HTTP response arrived. HTTP success does not imply API success: inspect the response's retval or error fields for that method.

jsonapi.encode(value) and jsonapi.decode(text) convert JSON, returning nil, error on failure. Use jsonapi.null for JSON null and jsonapi.array() for an empty array. Ordinary empty tables encode as objects; consecutive integer keys encode as arrays. Mixed keys, holes, cyclic tables, and nesting over 32 levels are rejected. Strings use UTF-8.

Qt JSON uses double precision: numbers outside the exact 53-bit range are rejected rather than silently rounded. Use string identifiers where the API accepts them; methods requiring larger numeric integers need a different JSON representation/client. Responses and individual event frames are limited to 8 MiB. Calls are synchronous, so use the standalone runner for lengthy jobs; a request invoked from the plugin GUI can block it until completion/timeout.

Event-driven scripts (standalone runner)

local count, err, status = jsonapi.subscribe(0, function(envelope)
    if envelope.event then
        print(assert(jsonapi.encode(envelope.event)))
        return false -- stop after the first event; omit to keep listening
    end
    -- The first envelope contains the registration result. Check its retval
    -- according to your RetroShare build's error-condition serialization.
end)
assert(count, err)

subscribe(eventType, callback) uses /rsEvents/registerEventsHandler and parses Server-Sent Events, including fragmented/multiline frames. Type 0 subscribes to all events; other numeric types come from your build's RsEventType. The callback receives each decoded envelope, including the initial registration result. It can make jsonapi.call requests and returns false to stop. Success returns envelopeCount, nil, httpStatus. Connection failures, malformed JSON, callback errors and disconnections return nil, error, httpStatus. There is no automatic reconnect or event replay.

The configured timeout covers establishing the stream. Once established it waits indefinitely, including quiet periods; stop via callback or Ctrl+C. Streaming is only enabled in the standalone runner so a persistent subscription cannot lock the plugin GUI. The plugin retains its existing native event triggers.

Migrating existing scripts

Existing peers.*, chat.*, config.*, files.* bindings and Lua4RS triggers remain available in the plugin. They are not provided by the standalone runner and are not automatically translated to HTTP. Port each operation to jsonapi.call and, for event scripts, to jsonapi.subscribe callbacks. The runner has standard Lua print, libraries, and arg[0]/arg[1] script arguments, but no GUI editor or built-in timer scheduler.

For example, peers.getFriendList() becomes the request shown above. Sending chat uses /rsChats/sendChat with the id and msg parameters; confirm the ChatId representation against your build before sending.

Verification

python tests/test_jsonapi.py jsonapi-runner/release/lua4rs-jsonapi.exe

This starts a loopback mock server and tests authentication, UTF-8, JSON objects/arrays/null, invalid inputs, redirects, HTTP errors, malformed replies, timeouts, SSE framing, callback errors, nested calls and disconnects. It never connects to a real RetroShare account. Real-server integration must still be checked against your enabled API and credentials.

Functions browser

The GUI separates JSON API endpoints, JSON API client helpers, and Native Lua helpers (GUI only). Search includes endpoint names, input types, and response fields. Double-click a callable entry to insert a template; hover over it for its inputs and response fields. Category headings do not insert code.

The endpoint catalogue is a checked-in snapshot of RetroShare's generated jsonapi-wrappers.inl, not live server discovery. A server with different build options or a different version may expose different endpoints. Manual wrappers are not included. Regenerate it after updating RetroShare:

python tools/generate-api-catalog.py ../../jsonapi-generator/src/jsonapi-wrappers.inl

Define the input variables shown in the inserted template before running it. The template checks for missing inputs and prints the JSON response. Types are the source C++ types: IDs require strings, arrays can use jsonapi.array(), and complex structures require the server's serialized JSON fields. The catalogue does not generate full schemas for these structures. Inspect result.retval when present; an HTTP success does not necessarily mean the operation succeeded. Calls may change RetroShare state depending on the selected endpoint.

Streaming endpoints are labelled and do not insert jsonapi.call templates. Use Automation triggers in the GUI. The standalone runner's jsonapi.subscribe supports the RetroShare event stream; it is not a generic streaming API client.