mirror of
https://github.com/DarkflameUniverse/DarkflameServer.git
synced 2026-11-20 10:45:27 +00:00
feat(dashboard): the zone file API, with zone edit locks
/api/v1/zones/{zoneId}: send a zone's edited files (multipart), follow the reload,
list, restore and clear the zone's sets, and take, release and look at its lock.
Every request needs an API key that names the zones_publish permission, an owner at
zone_publish_gm_level, and HTTPS or the server's own machine; refusals are counted
per address and every use is in the audit log. A publish is checked at its headers
before any of its body is taken, the files are checked and written on a worker
thread, and the zone's instances are replaced through the world reload, held while
players are there unless told to move them.
The Worlds page lists each zone's editors and lock holder for an admin.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -67,6 +67,7 @@
|
||||
#include "LiveWorld.h"
|
||||
#include "LiveUpdateRoutes.h"
|
||||
#include "WorldReloadRoutes.h"
|
||||
#include "ZonePublishRoutes.h"
|
||||
#include "master/WorldFiles.h"
|
||||
#include "Scenery.h"
|
||||
#include "Workers.h"
|
||||
@@ -377,7 +378,10 @@ namespace {
|
||||
handlers.On<ServerTraffic>(Master::SERVER_TRAFFIC, [](const ServerTraffic& report, const SystemAddress&) { Traffic::Ingest(report); });
|
||||
handlers.On<ProfileResult>(Master::PROFILE_RESULT, [](const ProfileResult& result, const SystemAddress&) { Performance::IngestProfile(result); });
|
||||
handlers.On<LiveUpdateStatus>(Master::LIVE_UPDATE_STATUS, [](const LiveUpdateStatus& status, const SystemAddress&) { LiveUpdateRoutes::HandleStatus(status); });
|
||||
handlers.On<WorldFilesStatus>(Master::WORLD_FILES_STATUS, [](const WorldFilesStatus& status, const SystemAddress&) { WorldReloadRoutes::HandleStatus(status); });
|
||||
handlers.On<WorldFilesStatus>(Master::WORLD_FILES_STATUS, [](const WorldFilesStatus& status, const SystemAddress&) {
|
||||
WorldReloadRoutes::HandleStatus(status);
|
||||
ZonePublishRoutes::HandleStatus(status);
|
||||
});
|
||||
return handlers;
|
||||
}();
|
||||
return handlers;
|
||||
@@ -594,6 +598,7 @@ int main(int argc, char** argv) {
|
||||
LiveWorld::RegisterRoutes();
|
||||
LiveUpdateRoutes::RegisterRoutes();
|
||||
WorldReloadRoutes::RegisterRoutes();
|
||||
ZonePublishRoutes::RegisterRoutes();
|
||||
Inspector::RegisterRoutes();
|
||||
CaptureReplay::RegisterRoutes();
|
||||
RegisterCDClientBrowserRoutes();
|
||||
@@ -683,6 +688,7 @@ int main(int argc, char** argv) {
|
||||
{ Profiler::Scope scope("Traffic::Update"); Traffic::Update(); }
|
||||
{ Profiler::Scope scope("Performance::Update"); Performance::Update(); }
|
||||
{ Profiler::Scope scope("ApiKeyService::Update"); ApiKeyService::Update(); }
|
||||
{ Profiler::Scope scope("ZonePublishRoutes::Update"); ZonePublishRoutes::Update(); }
|
||||
|
||||
// Broadcast dashboard updates periodically
|
||||
if (elapsedSinceBroadcast >= broadcastInterval) {
|
||||
@@ -697,6 +703,7 @@ int main(int argc, char** argv) {
|
||||
|
||||
// Cleanup: the worker threads first (they answer deferred requests), then the web server's connections
|
||||
Workers::Stop();
|
||||
ZonePublishRoutes::Shutdown();
|
||||
Game::web.Shutdown();
|
||||
ApiKeyService::Flush();
|
||||
Inspector::Shutdown();
|
||||
|
||||
@@ -82,7 +82,7 @@ namespace {
|
||||
// The key is in use and its owner may still sign in; the owner's GM level as of now
|
||||
std::optional<Owner> CheckKeyAndOwner(const IApiKeys::ApiKey& key) {
|
||||
const auto now = static_cast<int64_t>(std::time(nullptr));
|
||||
if (key.revokedAt != 0 || (key.expiresAt != 0 && key.expiresAt <= now)) return std::nullopt;
|
||||
if (!ApiKeys::InUse(key.revokedAt, key.expiresAt, now)) return std::nullopt;
|
||||
const auto account = Database::Get()->GetAccountById(key.accountId);
|
||||
if (account.contains("error") || account.value("banned", false) || account.value("locked", false)) return std::nullopt;
|
||||
const auto gmLevel = static_cast<uint8_t>(account.value("gm_level", 0));
|
||||
|
||||
158
dDashboardServer/auth/ZonePublishAuth.h
Normal file
158
dDashboardServer/auth/ZonePublishAuth.h
Normal file
@@ -0,0 +1,158 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
#include "ApiKeyScope.h"
|
||||
#include "eHTTPStatusCode.h"
|
||||
|
||||
/**
|
||||
* Who may use the zone file API (/api/v1/zones/..., docs/ZonePublish.md), checked on every request before any of
|
||||
* its body is taken. Pure, so every refusal is unit tested without a web server or a database: the caller looks up
|
||||
* the key and its owner (ApiKeyService does, on every request) and the request's addresses.
|
||||
*/
|
||||
namespace ZonePublishAuth {
|
||||
// The permission an API key needs in its own list (the zones.publish scope; permission names have no dots, so it
|
||||
// is kept as zones_publish and either spelling makes a key with it). A key with "all of the owner's permissions"
|
||||
// does not count, so a key can only write zone files when it was made for that.
|
||||
constexpr const char* SCOPE = "zones_publish";
|
||||
constexpr const char* SCOPE_ALIAS = "zones.publish";
|
||||
|
||||
inline bool IsLoopback(std::string_view address) {
|
||||
return address == "::1" || address == "localhost" || address.starts_with("127.") || address == "::ffff:127.0.0.1";
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a request's key travelled safely: over HTTPS, or from this machine. The dashboard itself speaks plain
|
||||
* HTTP; HTTPS is a reverse proxy's in front of it (behind_proxy=1), which says so in X-Forwarded-Proto.
|
||||
* @param peer The address the connection came from
|
||||
* @param forwardedFor The last X-Forwarded-For entry (what the proxy added), empty for none
|
||||
*/
|
||||
inline bool TransportAllowed(bool behindProxy, std::string_view peer, std::string_view forwardedFor, std::string_view forwardedProto) {
|
||||
// Without a proxy nothing is encrypted: this machine only. X-Forwarded-* from anyone is not believed.
|
||||
if (!behindProxy) return IsLoopback(peer);
|
||||
// Not through the proxy at all: a local caller
|
||||
if (forwardedFor.empty() && forwardedProto.empty()) return IsLoopback(peer);
|
||||
if (forwardedProto == "https") return true;
|
||||
// Through the proxy over plain HTTP: only from the proxy's own machine
|
||||
return IsLoopback(forwardedFor) && IsLoopback(peer);
|
||||
}
|
||||
|
||||
enum class eDenial : uint8_t {
|
||||
NONE,
|
||||
RATE_LIMITED, // too many refused requests from this address
|
||||
PLAIN_HTTP, // a key sent over plain HTTP from another machine
|
||||
NO_KEY, // no key, or one that is unknown, revoked, expired or whose owner can't sign in
|
||||
NOT_A_KEY, // signed in some other way (a session): this API takes API keys only
|
||||
SCOPE, // the key's permissions don't name zones.publish
|
||||
READ_ONLY, // a read-only key changing something
|
||||
GM_LEVEL, // the owner's GM level is below zone_publish_gm_level now
|
||||
};
|
||||
|
||||
struct Request {
|
||||
bool blocked{}; // FailureLimiter::Blocked for the address
|
||||
bool transportAllowed{};
|
||||
bool authenticated{}; // a credential was accepted (HTTPContext::isAuthenticated)
|
||||
const ApiKeys::Scope* key{}; // the API key that authenticated it, if one did
|
||||
uint8_t gmLevel{}; // the key owner's GM level, read from the database for this request
|
||||
uint8_t requiredLevel{}; // zone_publish_gm_level
|
||||
bool changes{}; // anything but a GET
|
||||
};
|
||||
|
||||
inline eDenial Check(const Request& request) {
|
||||
if (request.blocked) return eDenial::RATE_LIMITED;
|
||||
if (!request.transportAllowed) return eDenial::PLAIN_HTTP;
|
||||
if (!request.authenticated) return eDenial::NO_KEY;
|
||||
if (!request.key) return eDenial::NOT_A_KEY;
|
||||
if (!request.key->permissions.contains(SCOPE)) return eDenial::SCOPE;
|
||||
if (request.key->readOnly && request.changes) return eDenial::READ_ONLY;
|
||||
if (request.gmLevel < request.requiredLevel) return eDenial::GM_LEVEL;
|
||||
return eDenial::NONE;
|
||||
}
|
||||
|
||||
inline eHTTPStatusCode Status(eDenial denial) {
|
||||
switch (denial) {
|
||||
case eDenial::NONE: return eHTTPStatusCode::OK;
|
||||
case eDenial::RATE_LIMITED: return eHTTPStatusCode::TOO_MANY_REQUESTS;
|
||||
case eDenial::NO_KEY:
|
||||
case eDenial::NOT_A_KEY: return eHTTPStatusCode::UNAUTHORIZED;
|
||||
default: return eHTTPStatusCode::FORBIDDEN;
|
||||
}
|
||||
}
|
||||
|
||||
// The reply's "error"
|
||||
inline const char* Code(eDenial denial) {
|
||||
switch (denial) {
|
||||
case eDenial::NONE: return "";
|
||||
case eDenial::RATE_LIMITED: return "rate_limited";
|
||||
case eDenial::PLAIN_HTTP: return "https_required";
|
||||
case eDenial::NO_KEY: return "unauthorized";
|
||||
case eDenial::NOT_A_KEY: return "api_key_required";
|
||||
case eDenial::SCOPE: return "scope_required";
|
||||
case eDenial::READ_ONLY: return "read_only_key";
|
||||
case eDenial::GM_LEVEL: return "gm_level";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
inline const char* Message(eDenial denial) {
|
||||
switch (denial) {
|
||||
case eDenial::NONE: return "";
|
||||
case eDenial::RATE_LIMITED: return "Too many refused requests from this address; try again later";
|
||||
case eDenial::PLAIN_HTTP: return "API keys are only taken over HTTPS, or from the server's own machine";
|
||||
case eDenial::NO_KEY: return "Send a valid API key as 'Authorization: Bearer <key>'";
|
||||
case eDenial::NOT_A_KEY: return "This API takes API keys only";
|
||||
case eDenial::SCOPE: return "This API key doesn't have the zones.publish permission";
|
||||
case eDenial::READ_ONLY: return "This API key is read-only";
|
||||
case eDenial::GM_LEVEL: return "Your account's GM level is too low for zone files";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Refused requests per address, on top of each key's own rate limit: after maxFailures inside the window, the
|
||||
* address is refused outright until its failures age out. Times are unix seconds, passed in. Web thread only.
|
||||
*/
|
||||
class FailureLimiter {
|
||||
public:
|
||||
FailureLimiter(uint32_t maxFailures, int64_t windowSeconds) : m_Max(maxFailures), m_Window(windowSeconds) {}
|
||||
|
||||
bool Blocked(const std::string& address, int64_t now) {
|
||||
const auto it = m_Failures.find(address);
|
||||
if (it == m_Failures.end()) return false;
|
||||
Age(it->second, now);
|
||||
if (it->second.empty()) {
|
||||
m_Failures.erase(it);
|
||||
return false;
|
||||
}
|
||||
return it->second.size() >= m_Max;
|
||||
}
|
||||
|
||||
// Returns true when this failure is the one that blocks the address
|
||||
bool RecordFailure(const std::string& address, int64_t now) {
|
||||
if (m_Failures.size() > 10000) Prune(now);
|
||||
auto& failures = m_Failures[address];
|
||||
Age(failures, now);
|
||||
if (failures.size() >= m_Max) return false;
|
||||
failures.push_back(now);
|
||||
return failures.size() == m_Max;
|
||||
}
|
||||
|
||||
size_t Size() const { return m_Failures.size(); }
|
||||
|
||||
private:
|
||||
void Age(std::deque<int64_t>& failures, int64_t now) const {
|
||||
while (!failures.empty() && failures.front() <= now - m_Window) failures.pop_front();
|
||||
}
|
||||
void Prune(int64_t now) {
|
||||
std::erase_if(m_Failures, [&](auto& entry) { Age(entry.second, now); return entry.second.empty(); });
|
||||
}
|
||||
|
||||
uint32_t m_Max;
|
||||
int64_t m_Window;
|
||||
std::map<std::string, std::deque<int64_t>> m_Failures;
|
||||
};
|
||||
}
|
||||
@@ -14,6 +14,7 @@
|
||||
#include "PermissionGrantsLoader.h"
|
||||
#include "RequireAuthMiddleware.h"
|
||||
#include "RouteUtils.h"
|
||||
#include "ZonePublishAuth.h"
|
||||
|
||||
using namespace RouteUtils;
|
||||
using AccountRules::eAccountAction;
|
||||
@@ -213,7 +214,12 @@ namespace ApiKeyRoutes {
|
||||
key.permissions = std::string(ApiKeys::ALL_PERMISSIONS);
|
||||
} else if (requested.is_array()) {
|
||||
std::set<std::string> permissions;
|
||||
for (const auto& permission : requested) if (permission.is_string()) permissions.insert(permission.get<std::string>());
|
||||
for (const auto& permission : requested) {
|
||||
if (!permission.is_string()) continue;
|
||||
// The zone file API's scope is written zones.publish; permission names have no dots
|
||||
auto name = permission.get<std::string>();
|
||||
permissions.insert(name == ZonePublishAuth::SCOPE_ALIAS ? std::string(ZonePublishAuth::SCOPE) : name);
|
||||
}
|
||||
if (permissions.empty()) return JsonError(reply, eHTTPStatusCode::BAD_REQUEST, "Pick at least one permission");
|
||||
// Staff can't hand a key more than they have
|
||||
const auto refused = Permissions::NotGrantable(context.gmLevel, permissions, context.grants.get());
|
||||
|
||||
@@ -21,6 +21,7 @@ set(DASHBOARDROUTES_SOURCES
|
||||
"LiveWorld.cpp"
|
||||
"LiveUpdateRoutes.cpp"
|
||||
"WorldReloadRoutes.cpp"
|
||||
"ZonePublishRoutes.cpp"
|
||||
"SettingsRoutes.cpp"
|
||||
"Background.cpp"
|
||||
"DatabaseUsage.cpp"
|
||||
|
||||
@@ -14,7 +14,8 @@
|
||||
* description in the house style become query parameters and a request body:
|
||||
* "Query: ?range=24h|7d|30d, &files= (newest per server)" or "Query: after (the last id), limit (max 500)"
|
||||
* "Body: {name, enabled, parent (default root.xml)}" (also "Body (optional): {...}", "Body adds {...}")
|
||||
* Routes described as "(DataTables)" take the DataTables paging body. Pure (routes in, JSON out) so it can be tested.
|
||||
* Routes described as "(DataTables)" take the DataTables paging body; ones described as "(multipart)" take
|
||||
* multipart/form-data: the fields of their "Body: {...}" and file parts. Pure (routes in, JSON out) so it can be tested.
|
||||
*/
|
||||
namespace OpenApi {
|
||||
struct Route {
|
||||
@@ -203,7 +204,18 @@ namespace OpenApi {
|
||||
properties[param.name] = schema;
|
||||
example[param.name] = param.isList ? nlohmann::json::array() : nlohmann::json(param.choices.empty() ? "" : param.choices.front());
|
||||
}
|
||||
operation["requestBody"] = { {"required", false}, {"content", { {"application/json", { {"schema", { {"type", "object"}, {"properties", properties} }}, {"example", example} }} }} };
|
||||
if (route.description.find("(multipart)") != std::string::npos) {
|
||||
// File uploads: the fields from "Body: {...}", and any number of file parts
|
||||
properties["files"] = { {"type", "array"}, {"items", { {"type", "string"}, {"format", "binary"} }},
|
||||
{"description", "One part per file; each part's filename is the file's path"} };
|
||||
operation["requestBody"] = { {"required", true}, {"content", { {"multipart/form-data", { {"schema", { {"type", "object"}, {"properties", properties} }} }} }} };
|
||||
operation["responses"]["409"] = { {"description", "Conflict: {error, message}"} };
|
||||
operation["responses"]["413"] = { {"description", "Too large"} };
|
||||
operation["responses"]["422"] = { {"description", "Refused: {error: validation_failed, files: [{path, ok, errors: [{code, message, offset}]}]}"} };
|
||||
operation["responses"]["429"] = { {"description", "Too many requests"} };
|
||||
} else {
|
||||
operation["requestBody"] = { {"required", false}, {"content", { {"application/json", { {"schema", { {"type", "object"}, {"properties", properties} }}, {"example", example} }} }} };
|
||||
}
|
||||
}
|
||||
paths[path][method] = operation;
|
||||
}
|
||||
|
||||
@@ -92,6 +92,10 @@ namespace RouteUtils {
|
||||
Register(method, path, std::move(middleware), std::move(handler));
|
||||
}
|
||||
|
||||
void Document(eHTTPMethod method, const std::string& path, const std::string& permission, const std::string& description) {
|
||||
g_RouteDocs.push_back({ std::string(magic_enum::enum_name(method)), path, Permissions::Level(permission), description, permission, method == eHTTPMethod::GET });
|
||||
}
|
||||
|
||||
bool Can(const HTTPContext& context, const std::string& permission) {
|
||||
return context.isAuthenticated && Permissions::Allowed(context.gmLevel, permission, context.apiKey.get(), context.grants.get());
|
||||
}
|
||||
|
||||
@@ -260,6 +260,10 @@ namespace RouteUtils {
|
||||
void Route(eHTTPMethod method, const std::string& path, int16_t minGmLevel, const std::string& description, Handler handler);
|
||||
void Route(eHTTPMethod method, const std::string& path, const Perm& permission, const std::string& description, Handler handler);
|
||||
|
||||
// List a route that was registered with its own middleware (not through Route) in the API documentation;
|
||||
// permission: the permission its callers need
|
||||
void Document(eHTTPMethod method, const std::string& path, const std::string& permission, const std::string& description);
|
||||
|
||||
// Routes registered while one of these lives only read, even POSTs (lookups that send their query as a body), so
|
||||
// read-only API keys may use them. POST /api/tables/... (DataTables) always counts as a read.
|
||||
struct ReadRoutes {
|
||||
|
||||
1064
dDashboardServer/routes/ZonePublishRoutes.cpp
Normal file
1064
dDashboardServer/routes/ZonePublishRoutes.cpp
Normal file
File diff suppressed because it is too large
Load Diff
64
dDashboardServer/routes/ZonePublishRoutes.h
Normal file
64
dDashboardServer/routes/ZonePublishRoutes.h
Normal file
@@ -0,0 +1,64 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "json.hpp"
|
||||
|
||||
struct WorldFilesStatus;
|
||||
|
||||
/**
|
||||
* The zone file API (/api/v1/zones/..., docs/ZonePublish.md): an external level editor sends a zone's edited files,
|
||||
* which are checked, kept in the override folder and loaded by replacing the zone's instances. A thin layer: who
|
||||
* may is ZonePublishAuth (the key) and ZoneEditLock (the zone's lock), checking a set is ZonePublish, keeping it is
|
||||
* ZoneOverrideStore, and the reload is the world reload master already does (WorldReloader).
|
||||
*
|
||||
* Routes and their database use run on the main thread; reading and writing the files runs on one worker thread,
|
||||
* which touches nothing else and hands its result back to the main thread (Update).
|
||||
*/
|
||||
namespace ZonePublishRoutes {
|
||||
void RegisterRoutes();
|
||||
|
||||
// Master's world file status (WORLD_FILES_STATUS): how far the reloads asked for here have come
|
||||
void HandleStatus(const WorldFilesStatus& status);
|
||||
|
||||
// Main loop: finish what the worker did
|
||||
void Update();
|
||||
|
||||
// Stops the worker (a set being written finishes first)
|
||||
void Shutdown();
|
||||
|
||||
// What master counts per zone (WorldFilesStatus::Zone); present: the zone has instances that reported files
|
||||
struct ReloadCounters {
|
||||
bool present{};
|
||||
uint32_t requests{};
|
||||
uint32_t acted{};
|
||||
uint32_t playersMoved{};
|
||||
uint32_t failed{};
|
||||
uint16_t pending{};
|
||||
};
|
||||
|
||||
struct ReloadProgress {
|
||||
bool done{};
|
||||
uint32_t instances{};
|
||||
uint32_t playersMoved{};
|
||||
uint32_t failed{};
|
||||
};
|
||||
|
||||
/**
|
||||
* What a reload asked for when the counters were `before` has done by `now`: done once master took the request
|
||||
* and nothing of the zone is being replaced any more, or the zone has no instance left. Pure.
|
||||
*/
|
||||
inline ReloadProgress ProgressOf(const ReloadCounters& before, const ReloadCounters& now) {
|
||||
ReloadProgress progress;
|
||||
// No instance left (they were all stopped), or the counts started over: nothing more will come
|
||||
if (!now.present || now.requests < before.requests || now.acted < before.acted) {
|
||||
progress.done = true;
|
||||
return progress;
|
||||
}
|
||||
progress.instances = now.acted - before.acted;
|
||||
progress.playersMoved = now.playersMoved >= before.playersMoved ? now.playersMoved - before.playersMoved : 0;
|
||||
progress.failed = now.failed >= before.failed ? now.failed - before.failed : 0;
|
||||
progress.done = now.requests > before.requests && now.pending == 0;
|
||||
return progress;
|
||||
}
|
||||
}
|
||||
@@ -97,6 +97,27 @@
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if can.zone_editors_manage %}
|
||||
<div class="card mt-3" id="zoneEditingCard">
|
||||
<div class="card-header d-flex flex-wrap justify-content-between align-items-center gap-2">
|
||||
<h5 class="mb-0">Zone editors and locks</h5>
|
||||
<span class="small text-body-secondary" id="zoneEditingState"></span>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<p class="small text-body-secondary">Who may send a zone's edited files through the zone file API (<code>/api/v1/zones</code>). A zone has up to
|
||||
<span id="zoneEditingMax">10</span> editors; one account at a time holds its lock, and only the holder can send, restore or clear its files.
|
||||
A lock is kept until its holder releases it or it is taken away here.</p>
|
||||
<form class="row g-2 align-items-end mb-3" id="zoneEditorForm">
|
||||
<div class="col-auto"><label class="form-label small mb-0" for="zoneEditorZone">Zone ID</label>
|
||||
<input type="number" min="1" class="form-control form-control-sm" id="zoneEditorZone" required></div>
|
||||
<div class="col-auto"><label class="form-label small mb-0" for="zoneEditorAccount">Account (name or ID)</label>
|
||||
<input type="text" class="form-control form-control-sm" id="zoneEditorAccount" maxlength="64" required></div>
|
||||
<div class="col-auto"><button type="submit" class="btn btn-primary btn-sm">Add editor</button></div>
|
||||
</form>
|
||||
<div id="zoneEditingZones"><p class="text-body-secondary mb-0">Loading…</p></div>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
@@ -289,4 +310,58 @@
|
||||
})();
|
||||
</script>
|
||||
{% endif %}
|
||||
{% if can.zone_editors_manage %}
|
||||
<script>
|
||||
(function () {
|
||||
var box = document.getElementById('zoneEditingZones');
|
||||
function when(seconds) { return seconds ? new Date(seconds * 1000).toLocaleString() : ''; }
|
||||
|
||||
function show(d) {
|
||||
document.getElementById('zoneEditingMax').textContent = d.maxEditors;
|
||||
document.getElementById('zoneEditingState').textContent = d.enabled
|
||||
? 'Sending files needs GM ' + d.publishLevel + '+; managing this needs GM ' + d.adminLevel + '+'
|
||||
: 'Turned off (zone_override_dir is empty)';
|
||||
if (!d.zones.length) { box.innerHTML = '<p class="text-body-secondary mb-0">No zone has editors or a held lock.</p>'; return; }
|
||||
var rows = d.zones.map(function (z) {
|
||||
var editors = z.editors.map(function (e) {
|
||||
return '<span class="me-2 text-nowrap" title="Added by ' + esc(e.assignedBy) + ', ' + esc(when(e.assignedAt)) + '">' + esc(e.name) +
|
||||
' <button type="button" class="btn btn-link btn-sm p-0 align-baseline" data-remove-editor="' + esc(e.accountId) + '" data-zone="' + esc(z.zone) + '">remove</button></span>';
|
||||
}).join('') || '<span class="text-body-secondary">none</span>';
|
||||
var lock = z.holder
|
||||
? esc(z.holder) + ' <span class="text-body-secondary">since ' + esc(when(z.since)) + '</span> ' +
|
||||
'<button type="button" class="btn btn-outline-danger btn-sm ms-1" data-release-zone="' + esc(z.zone) + '">Take away</button>'
|
||||
: '<span class="text-body-secondary">nobody</span>';
|
||||
return '<tr><td>' + fmt.zone(z.zone, z.zoneName) + (z.state ? ' ' + fmt.badge(z.state, 'info') : '') + '</td><td>' + editors + '</td><td>' + lock + '</td></tr>';
|
||||
}).join('');
|
||||
box.innerHTML = '<div class="table-responsive"><table class="table table-sm align-middle mb-0"><thead><tr><th>Zone</th><th>Editors</th><th>Lock held by</th></tr></thead><tbody>' +
|
||||
rows + '</tbody></table></div>';
|
||||
}
|
||||
|
||||
function load() { api.get('/api/zone-editing').then(function (d) { if (d.success) show(d); }).catch(function () {}); }
|
||||
|
||||
document.getElementById('zoneEditorForm').addEventListener('submit', function (e) {
|
||||
e.preventDefault();
|
||||
var zone = +document.getElementById('zoneEditorZone').value;
|
||||
var account = document.getElementById('zoneEditorAccount').value.trim();
|
||||
if (!zone || !account) return;
|
||||
api.action('/api/zone-editing/' + zone + '/editors', { account: account }, 'Editor added').then(function () {
|
||||
document.getElementById('zoneEditorAccount').value = '';
|
||||
load();
|
||||
}).catch(function () {});
|
||||
});
|
||||
box.addEventListener('click', function (e) {
|
||||
var remove = e.target.closest('[data-remove-editor]');
|
||||
if (remove) {
|
||||
api.action('/api/zone-editing/' + remove.dataset.zone + '/editors/remove', { accountId: +remove.dataset.removeEditor }, 'Editor removed').then(load).catch(function () {});
|
||||
return;
|
||||
}
|
||||
var release = e.target.closest('[data-release-zone]');
|
||||
if (!release) return;
|
||||
if (!confirm('Take this zone\'s lock away from its holder? They can no longer send its files until they take the lock again.')) return;
|
||||
api.action('/api/zone-editing/' + release.dataset.releaseZone + '/release', {}, 'Lock released').then(load).catch(function () {});
|
||||
});
|
||||
load();
|
||||
})();
|
||||
</script>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
Reference in New Issue
Block a user