diff --git a/CHANGELOG b/CHANGELOG
index a9f0e58c3e..9c1d23e78a 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,6 +1,31 @@
v3.5.1 (XXXX-XX-XX)
-------------------
+* Added startup option `--cluster.max-number-of-shards` for restricting the
+ maximum number of shards when creating new collections. The default
+ value for this setting is `1000`, which is also the previously hard-coded
+ built-in limit. A value of `0` for this option means "unrestricted".
+ When the setting is adjusted, it will not affect already existing
+ collections, but only collections that are created or restored
+ afterwards.
+
+* Added startup options for managing the replication factor for newly
+ created collections:
+
+ - `--cluster.min-replication-factor`: this settings controls the minimum
+ replication factor value that is permitted when creating new collections.
+ No collections can be created which have a replication factor value
+ below this setting's value. The default value is 1.
+ - `--cluster.max-replication-factor`: this settings controls the maximum
+ replication factor value that is permitted when creating new collections.
+ No collections can be created which have a replication factor value
+ above this setting's value. The default value is 10.
+ - `--cluster.default-replication-factor`: this settings controls the default
+ replication factor value that is used when creating new collections and
+ no value of replication factor has been specified.
+ If no value is set for this option, the value of the option
+ `--cluster.min-replication-factor` will be used.
+
* Fixed unintended multiple unlock commands from coordinator to
transaction locked db servers.
diff --git a/arangod/Cluster/ClusterFeature.cpp b/arangod/Cluster/ClusterFeature.cpp
index 8fad62843f..6f15f3c337 100644
--- a/arangod/Cluster/ClusterFeature.cpp
+++ b/arangod/Cluster/ClusterFeature.cpp
@@ -124,10 +124,22 @@ void ClusterFeature::collectOptions(std::shared_ptr options) {
"this server's advertised endpoint (e.g. external IP "
"address or load balancer, optional)",
new StringParameter(&_myAdvertisedEndpoint));
+
+ options->addOption("--cluster.default-replication-factor",
+ "default replication factor for new collections",
+ new UInt32Parameter(&_defaultReplicationFactor)).setIntroducedIn(30501);
options->addOption("--cluster.system-replication-factor",
"replication factor for system collections",
new UInt32Parameter(&_systemReplicationFactor));
+
+ options->addOption("--cluster.min-replication-factor",
+ "minimum replication factor for new collections",
+ new UInt32Parameter(&_minReplicationFactor)).setIntroducedIn(30501);
+
+ options->addOption("--cluster.max-replication-factor",
+ "maximum replication factor for new collections (0 = unrestricted)",
+ new UInt32Parameter(&_maxReplicationFactor)).setIntroducedIn(30501);
options->addOption(
"--cluster.create-waits-for-sync-replication",
@@ -135,6 +147,10 @@ void ClusterFeature::collectOptions(std::shared_ptr options) {
new BooleanParameter(&_createWaitsForSyncReplication),
arangodb::options::makeFlags(arangodb::options::Flags::Hidden));
+ options->addOption("--cluster.max-number-of-shards",
+ "maximum number of shards when creating new collections (0 = unrestricted)",
+ new UInt32Parameter(&_maxNumberOfShards)).setIntroducedIn(30501);
+
options->addOption(
"--cluster.index-create-timeout",
"amount of time (in seconds) the coordinator will wait for an index to "
@@ -155,6 +171,49 @@ void ClusterFeature::validateOptions(std::shared_ptr options) {
<< "details.";
FATAL_ERROR_EXIT();
}
+
+ if (_minReplicationFactor == 0) {
+ // min replication factor must not be 0
+ LOG_TOPIC("2fbdd", FATAL, arangodb::Logger::CLUSTER)
+ << "Invalid value for `--cluster.min-replication-factor`. The value must be at least 1";
+ FATAL_ERROR_EXIT();
+ }
+
+ if (_maxReplicationFactor > 10) {
+ // 10 is a hard-coded limit for the replication factor
+ LOG_TOPIC("886c6", FATAL, arangodb::Logger::CLUSTER)
+ << "Invalid value for `--cluster.max-replication-factor`. The value must not exceed 10";
+ FATAL_ERROR_EXIT();
+ }
+
+ TRI_ASSERT(_minReplicationFactor > 0);
+ if (!options->processingResult().touched("cluster.default-replication-factor")) {
+ // no default replication factor set. now use the minimum value, which is
+ // guaranteed to be at least 1
+ _defaultReplicationFactor = _minReplicationFactor;
+ }
+
+ if (_defaultReplicationFactor == 0) {
+ // default replication factor must not be 0
+ LOG_TOPIC("fc8a9", FATAL, arangodb::Logger::CLUSTER)
+ << "Invalid value for `--cluster.default-replication-factor`. The value must be at least 1";
+ FATAL_ERROR_EXIT();
+ }
+
+ if (_defaultReplicationFactor > 0 &&
+ _maxReplicationFactor > 0 &&
+ _defaultReplicationFactor > _maxReplicationFactor) {
+ LOG_TOPIC("6cf0c", FATAL, arangodb::Logger::CLUSTER)
+ << "Invalid value for `--cluster.default-replication-factor`. Must not be higher than `--cluster.max-replication-factor`";
+ FATAL_ERROR_EXIT();
+ }
+
+ if (_defaultReplicationFactor > 0 &&
+ _defaultReplicationFactor < _minReplicationFactor) {
+ LOG_TOPIC("b9aea", FATAL, arangodb::Logger::CLUSTER)
+ << "Invalid value for `--cluster.default-replication-factor`. Must not be lower than `--cluster.min-replication-factor`";
+ FATAL_ERROR_EXIT();
+ }
// check if the cluster is enabled
_enableCluster = !_agencyEndpoints.empty();
diff --git a/arangod/Cluster/ClusterFeature.h b/arangod/Cluster/ClusterFeature.h
index ec304b0b42..667257c34c 100644
--- a/arangod/Cluster/ClusterFeature.h
+++ b/arangod/Cluster/ClusterFeature.h
@@ -66,7 +66,11 @@ class ClusterFeature : public application_features::ApplicationFeature {
std::string _myRole;
std::string _myEndpoint;
std::string _myAdvertisedEndpoint;
- uint32_t _systemReplicationFactor = 2;
+ std::uint32_t _defaultReplicationFactor = 0; // a value of 0 means it will use the min replication factor
+ std::uint32_t _systemReplicationFactor = 2;
+ std::uint32_t _minReplicationFactor = 1;
+ std::uint32_t _maxReplicationFactor = 10; // maximum replication factor (0 = unrestricted)
+ std::uint32_t _maxNumberOfShards = 1000; // maximum number of shards (0 = unrestricted)
bool _createWaitsForSyncReplication = true;
double _indexCreationTimeout = 3600.0;
@@ -88,7 +92,11 @@ class ClusterFeature : public application_features::ApplicationFeature {
return _createWaitsForSyncReplication;
};
double indexCreationTimeout() const { return _indexCreationTimeout; }
- uint32_t systemReplicationFactor() { return _systemReplicationFactor; };
+ uint32_t defaultReplicationFactor() { return _defaultReplicationFactor; }
+ uint32_t systemReplicationFactor() { return _systemReplicationFactor; }
+ std::uint32_t maxNumberOfShards() const { return _maxNumberOfShards; }
+ std::uint32_t minReplicationFactor() const { return _minReplicationFactor; }
+ std::uint32_t maxReplicationFactor() const { return _maxReplicationFactor; }
void stop() override final;
diff --git a/arangod/RestHandler/RestReplicationHandler.cpp b/arangod/RestHandler/RestReplicationHandler.cpp
index 13bafda3ad..8c346212e8 100644
--- a/arangod/RestHandler/RestReplicationHandler.cpp
+++ b/arangod/RestHandler/RestReplicationHandler.cpp
@@ -49,6 +49,7 @@
#include "RestServer/DatabaseFeature.h"
#include "RestServer/QueryRegistryFeature.h"
#include "RestServer/ServerIdFeature.h"
+#include "Sharding/ShardingInfo.h"
#include "StorageEngine/EngineSelectorFeature.h"
#include "StorageEngine/PhysicalCollection.h"
#include "StorageEngine/StorageEngine.h"
@@ -1090,6 +1091,11 @@ Result RestReplicationHandler::processRestoreCollectionCoordinator(
return Result();
}
+ Result res = ShardingInfo::validateShardsAndReplicationFactor(parameters);
+ if (res.fail()) {
+ return res;
+ }
+
auto& dbName = _vocbase.name();
ClusterInfo* ci = ClusterInfo::instance();
@@ -1185,7 +1191,10 @@ Result RestReplicationHandler::processRestoreCollectionCoordinator(
if (!isValidReplFactorSlice) {
if (replicationFactor == 0) {
- replicationFactor = 1;
+ replicationFactor = application_features::ApplicationServer::getFeature("Cluster")->defaultReplicationFactor();
+ if (replicationFactor == 0) {
+ replicationFactor = 1;
+ }
}
TRI_ASSERT(replicationFactor > 0);
toMerge.add(StaticStrings::ReplicationFactor, VPackValue(replicationFactor));
diff --git a/arangod/Sharding/ShardingInfo.cpp b/arangod/Sharding/ShardingInfo.cpp
index 1d8aaffb70..2c8e3184e7 100644
--- a/arangod/Sharding/ShardingInfo.cpp
+++ b/arangod/Sharding/ShardingInfo.cpp
@@ -26,6 +26,7 @@
#include "Basics/Exceptions.h"
#include "Basics/StaticStrings.h"
#include "Basics/VelocyPackHelper.h"
+#include "Cluster/ClusterFeature.h"
#include "Cluster/ServerState.h"
#include "Logger/Logger.h"
#include "Sharding/ShardingFeature.h"
@@ -61,10 +62,18 @@ ShardingInfo::ShardingInfo(arangodb::velocypack::Slice info, LogicalCollection*
VPackSlice shardKeysSlice = info.get(StaticStrings::ShardKeys);
if (ServerState::instance()->isCoordinator()) {
- if ((_numberOfShards == 0 && !isSmart) || _numberOfShards > 1000) {
+ if (_numberOfShards == 0 && !isSmart) {
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_BAD_PARAMETER,
"invalid number of shards");
}
+ // intentionally no call to validateNumberOfShards here,
+ // because this constructor is called from the constructor of
+ // LogicalCollection, and we want LogicalCollection to be created
+ // with any configured number of shards in case the maximum allowed
+ // number of shards is set or decreased in a cluster with already
+ // existing collections that would violate the setting.
+ // so we validate the number of shards against the maximum only
+ // when a collection is created by a user, and on a restore
}
VPackSlice distributeShardsLike = info.get(StaticStrings::DistributeShardsLike);
@@ -88,7 +97,7 @@ ShardingInfo::ShardingInfo(arangodb::velocypack::Slice info, LogicalCollection*
_avoidServers.push_back(i.copyString());
} else {
LOG_TOPIC("e5bc6", ERR, arangodb::Logger::FIXME)
- << "avoidServers must be a vector of strings we got "
+ << "avoidServers must be a vector of strings, we got "
<< avoidServersSlice.toJson() << ". discarding!";
_avoidServers.clear();
break;
@@ -97,13 +106,14 @@ ShardingInfo::ShardingInfo(arangodb::velocypack::Slice info, LogicalCollection*
}
}
+ bool isSatellite = false;
auto replicationFactorSlice = info.get(StaticStrings::ReplicationFactor);
if (!replicationFactorSlice.isNone()) {
bool isError = true;
if (replicationFactorSlice.isNumber()) {
_replicationFactor = replicationFactorSlice.getNumber();
// mop: only allow satellite collections to be created explicitly
- if (_replicationFactor > 0 && _replicationFactor <= 10) {
+ if (_replicationFactor > 0) {
isError = false;
#ifdef USE_ENTERPRISE
} else if (_replicationFactor == 0) {
@@ -120,6 +130,7 @@ ShardingInfo::ShardingInfo(arangodb::velocypack::Slice info, LogicalCollection*
_distributeShardsLike = "";
_avoidServers.clear();
isError = false;
+ isSatellite = true;
}
#endif
if (isError) {
@@ -128,25 +139,27 @@ ShardingInfo::ShardingInfo(arangodb::velocypack::Slice info, LogicalCollection*
}
}
- auto minReplicationFactorSlice = info.get(StaticStrings::MinReplicationFactor);
- if (!minReplicationFactorSlice.isNone()) {
- if (minReplicationFactorSlice.isNumber()) {
- _minReplicationFactor = minReplicationFactorSlice.getNumber();
- if (_minReplicationFactor > _replicationFactor) {
+ if (!isSatellite) {
+ auto minReplicationFactorSlice = info.get(StaticStrings::MinReplicationFactor);
+ if (!minReplicationFactorSlice.isNone()) {
+ if (minReplicationFactorSlice.isNumber()) {
+ _minReplicationFactor = minReplicationFactorSlice.getNumber();
+ if (_minReplicationFactor > _replicationFactor) {
+ THROW_ARANGO_EXCEPTION_MESSAGE(
+ TRI_ERROR_BAD_PARAMETER,
+ "minReplicationFactor cannot be larger than replicationFactor (" +
+ basics::StringUtils::itoa(_minReplicationFactor) + " > " +
+ basics::StringUtils::itoa(_replicationFactor) + ")");
+ }
+ if (_minReplicationFactor == 0 && _replicationFactor != 0) {
+ THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_BAD_PARAMETER,
+ "minReplicationFactor cannot be 0");
+ }
+ } else {
THROW_ARANGO_EXCEPTION_MESSAGE(
TRI_ERROR_BAD_PARAMETER,
- "minReplicationFactor cannot be larger then replicationFactor (" +
- basics::StringUtils::itoa(_minReplicationFactor) + " > " +
- basics::StringUtils::itoa(_replicationFactor) + ")");
+ "minReplicationFactor needs to be an integer number");
}
- if (_minReplicationFactor == 0 && _replicationFactor != 0) {
- THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_BAD_PARAMETER,
- "minReplicationFactor cannot be 0");
- }
- } else {
- THROW_ARANGO_EXCEPTION_MESSAGE(
- TRI_ERROR_BAD_PARAMETER,
- "minReplicationFactor needs to be an integer number");
}
}
@@ -363,7 +376,7 @@ void ShardingInfo::replicationFactor(size_t replicationFactor) {
if (replicationFactor < _minReplicationFactor) {
THROW_ARANGO_EXCEPTION_MESSAGE(
TRI_ERROR_BAD_PARAMETER,
- "replicationFactor cannot be smaller then minReplicationFactor (" +
+ "replicationFactor cannot be smaller than minReplicationFactor (" +
basics::StringUtils::itoa(_replicationFactor) + " < " +
basics::StringUtils::itoa(_minReplicationFactor) + ")");
}
@@ -379,7 +392,7 @@ void ShardingInfo::minReplicationFactor(size_t minReplicationFactor) {
if (minReplicationFactor > _replicationFactor) {
THROW_ARANGO_EXCEPTION_MESSAGE(
TRI_ERROR_BAD_PARAMETER,
- "minReplicationFactor cannot be larger then replicationFactor (" +
+ "minReplicationFactor cannot be larger than replicationFactor (" +
basics::StringUtils::itoa(_minReplicationFactor) + " > " +
basics::StringUtils::itoa(_replicationFactor) + ")");
}
@@ -390,7 +403,7 @@ void ShardingInfo::setMinAndMaxReplicationFactor(size_t minimal, size_t maximal)
if (minimal > maximal) {
THROW_ARANGO_EXCEPTION_MESSAGE(
TRI_ERROR_BAD_PARAMETER,
- "minReplicationFactor cannot be larger then replicationFactor (" +
+ "minReplicationFactor cannot be larger than replicationFactor (" +
basics::StringUtils::itoa(minimal) + " > " +
basics::StringUtils::itoa(maximal) + ")");
}
@@ -459,3 +472,45 @@ int ShardingInfo::getResponsibleShard(arangodb::velocypack::Slice slice, bool do
return _shardingStrategy->getResponsibleShard(slice, docComplete, shardID,
usesDefaultShardKeys, key);
}
+
+Result ShardingInfo::validateShardsAndReplicationFactor(arangodb::velocypack::Slice slice) {
+ Result res;
+
+ auto const* cl = application_features::ApplicationServer::getFeature("Cluster");
+
+ auto numberOfShardsSlice = slice.get(StaticStrings::NumberOfShards);
+ if (numberOfShardsSlice.isNumber()) {
+ uint32_t const maxNumberOfShards = cl->maxNumberOfShards();
+ uint32_t numberOfShards = numberOfShardsSlice.getNumber();
+ if (maxNumberOfShards > 0 &&
+ numberOfShards > maxNumberOfShards) {
+ res.reset(TRI_ERROR_CLUSTER_TOO_MANY_SHARDS,
+ std::string("too many shards. maximum number of shards is ") + std::to_string(maxNumberOfShards));
+ }
+ }
+
+ auto replicationFactorSlice = slice.get(StaticStrings::ReplicationFactor);
+ if (replicationFactorSlice.isNumber()) {
+ uint32_t const minReplicationFactor = cl->minReplicationFactor();
+ uint32_t const maxReplicationFactor = cl->maxReplicationFactor();
+
+ int64_t replicationFactorProbe = replicationFactorSlice.getNumber();
+ if (replicationFactorProbe <= 0) {
+ res.reset(TRI_ERROR_BAD_PARAMETER, "invalid value for replicationFactor");
+ } else {
+ uint32_t replicationFactor = replicationFactorSlice.getNumber();
+
+ if (replicationFactor > maxReplicationFactor &&
+ maxReplicationFactor > 0) {
+ res.reset(TRI_ERROR_BAD_PARAMETER,
+ std::string("replicationFactor must not be higher than maximum allowed replicationFactor (") + std::to_string(maxReplicationFactor) + ")");
+ } else if (replicationFactor < minReplicationFactor &&
+ minReplicationFactor > 0) {
+ res.reset(TRI_ERROR_BAD_PARAMETER,
+ std::string("replicationFactor must not be lower than minimum allowed replicationFactor (") + std::to_string(minReplicationFactor) + ")");
+ }
+ }
+ }
+
+ return res;
+}
diff --git a/arangod/Sharding/ShardingInfo.h b/arangod/Sharding/ShardingInfo.h
index 8b7d1390b8..bc4b957c5b 100644
--- a/arangod/Sharding/ShardingInfo.h
+++ b/arangod/Sharding/ShardingInfo.h
@@ -24,6 +24,8 @@
#ifndef ARANGOD_CLUSTER_SHARDING_INFO_H
#define ARANGOD_CLUSTER_SHARDING_INFO_H 1
+#include "Basics/Result.h"
+
#include
#include
#include
@@ -75,6 +77,10 @@ class ShardingInfo {
/// in its constructor, after the shardingInfo has been set up already
void numberOfShards(size_t numberOfShards);
+ /// @brief validates the number of shards and the replication factor
+ /// in slice against the minimum and maximum configured values
+ static Result validateShardsAndReplicationFactor(arangodb::velocypack::Slice slice);
+
bool usesDefaultShardKeys() const;
std::vector const& shardKeys() const;
diff --git a/arangod/V8Server/v8-vocbase.cpp b/arangod/V8Server/v8-vocbase.cpp
index 37d3570900..3ffaba22b7 100644
--- a/arangod/V8Server/v8-vocbase.cpp
+++ b/arangod/V8Server/v8-vocbase.cpp
@@ -50,6 +50,7 @@
#include "Basics/Utf8Helper.h"
#include "Basics/conversions.h"
#include "Basics/tri-strings.h"
+#include "Cluster/ClusterFeature.h"
#include "Cluster/ClusterInfo.h"
#include "Cluster/ServerState.h"
#include "GeneralServer/AuthenticationFeature.h"
@@ -2065,6 +2066,36 @@ void TRI_InitV8VocBridge(v8::Isolate* isolate, v8::Handle context,
v8::Boolean::New(isolate,
StatisticsFeature::enabled()))
.FromMaybe(false); // ignore result //, v8::ReadOnly);
+
+ // replication factors
+ context->Global()
+ ->DefineOwnProperty(TRI_IGETC,
+ TRI_V8_ASCII_STRING(isolate, "DEFAULT_REPLICATION_FACTOR"),
+ v8::Number::New(isolate,
+ application_features::ApplicationServer::getFeature("Cluster")->defaultReplicationFactor()), v8::ReadOnly)
+ .FromMaybe(false); // ignore result
+
+ context->Global()
+ ->DefineOwnProperty(TRI_IGETC,
+ TRI_V8_ASCII_STRING(isolate, "MIN_REPLICATION_FACTOR"),
+ v8::Number::New(isolate,
+ application_features::ApplicationServer::getFeature("Cluster")->minReplicationFactor()), v8::ReadOnly)
+ .FromMaybe(false); // ignore result
+
+ context->Global()
+ ->DefineOwnProperty(TRI_IGETC,
+ TRI_V8_ASCII_STRING(isolate, "MAX_REPLICATION_FACTOR"),
+ v8::Number::New(isolate,
+ application_features::ApplicationServer::getFeature("Cluster")->maxReplicationFactor()), v8::ReadOnly)
+ .FromMaybe(false); // ignore result
+
+ // max number of shards
+ context->Global()
+ ->DefineOwnProperty(TRI_IGETC,
+ TRI_V8_ASCII_STRING(isolate, "MAX_NUMBER_OF_SHARDS"),
+ v8::Number::New(isolate,
+ application_features::ApplicationServer::getFeature("Cluster")->maxNumberOfShards()), v8::ReadOnly)
+ .FromMaybe(false); // ignore result
// a thread-global variable that will is supposed to contain the AQL module
// do not remove this, otherwise AQL queries will break
diff --git a/arangod/VocBase/Methods/Collections.cpp b/arangod/VocBase/Methods/Collections.cpp
index 0db56b20d6..b9c2646115 100644
--- a/arangod/VocBase/Methods/Collections.cpp
+++ b/arangod/VocBase/Methods/Collections.cpp
@@ -40,6 +40,7 @@
#include "Scheduler/Scheduler.h"
#include "Scheduler/SchedulerFeature.h"
#include "Sharding/ShardingFeature.h"
+#include "Sharding/ShardingInfo.h"
#include "StorageEngine/PhysicalCollection.h"
#include "Transaction/V8Context.h"
#include "Utils/Events.h"
@@ -259,6 +260,13 @@ Result Collections::create(TRI_vocbase_t& vocbase,
builder.openArray();
for (auto const& info : infos) {
TRI_ASSERT(builder.isOpenArray());
+
+ if (ServerState::instance()->isCoordinator()) {
+ Result res = ShardingInfo::validateShardsAndReplicationFactor(info.properties);
+ if (res.fail()) {
+ return res;
+ }
+ }
if (info.name.empty()) {
events::CreateCollection(vocbase.name(), info.name, TRI_ERROR_ARANGO_ILLEGAL_NAME);
@@ -275,6 +283,16 @@ Result Collections::create(TRI_vocbase_t& vocbase,
arangodb::velocypack::Value(static_cast(info.collectionType)));
helper.add(arangodb::StaticStrings::DataSourceName,
arangodb::velocypack::Value(info.name));
+
+ if (ServerState::instance()->isCoordinator()) {
+ // patch default replicationFactor into the data
+ VPackSlice replicationFactorSlice = info.properties.get(arangodb::StaticStrings::ReplicationFactor);
+ if (replicationFactorSlice.isNone()) {
+ helper.add(arangodb::StaticStrings::ReplicationFactor,
+ VPackValue(application_features::ApplicationServer::getFeature("Cluster")->defaultReplicationFactor()));
+ }
+ }
+
helper.close();
VPackBuilder merged =
VPackCollection::merge(info.properties, helper.slice(), false, true);
@@ -566,6 +584,11 @@ Result Collections::updateProperties(LogicalCollection& collection,
auto info = ci->getCollection(collection.vocbase().name(),
std::to_string(collection.id()));
+ Result res = ShardingInfo::validateShardsAndReplicationFactor(props);
+ if (res.fail()) {
+ return res;
+ }
+
return info->properties(props, partialUpdate);
} else {
auto ctx = transaction::V8Context::CreateWhenRequired(collection.vocbase(), false);
diff --git a/js/apps/system/_admin/aardvark/APP/aardvark.js b/js/apps/system/_admin/aardvark/APP/aardvark.js
index 64200313b9..20a75ed87b 100644
--- a/js/apps/system/_admin/aardvark/APP/aardvark.js
+++ b/js/apps/system/_admin/aardvark/APP/aardvark.js
@@ -90,7 +90,11 @@ router.get('/config.js', function (req, res) {
engine: db._engine().name,
statisticsEnabled: internal.enabledStatistics(),
foxxStoreEnabled: !internal.isFoxxStoreDisabled(),
- foxxApiEnabled: !internal.isFoxxApiDisabled()
+ foxxApiEnabled: !internal.isFoxxApiDisabled(),
+ minReplicationFactor: internal.minReplicationFactor,
+ maxReplicationFactor: internal.maxReplicationFactor,
+ defaultReplicationFactor: internal.defaultReplicationFactor,
+ maxNumberOfShards: internal.maxNumberOfShards
})}`
);
})
diff --git a/js/apps/system/_admin/aardvark/APP/frontend/build/app.min.js b/js/apps/system/_admin/aardvark/APP/frontend/build/app.min.js
index 973a8300bf..a6045fe2d6 100644
--- a/js/apps/system/_admin/aardvark/APP/frontend/build/app.min.js
+++ b/js/apps/system/_admin/aardvark/APP/frontend/build/app.min.js
@@ -1 +1 @@
-!function(){"use strict";var i=null;window.isCoordinator=function(t){null===i?$.ajax("cluster/amICoordinator",{async:!0,success:function(e){t(!1,i=e)},error:function(e){t(!0,i=e)}}):t(!1,i)},window.versionHelper={fromString:function(e){var t=e.replace(/-[a-zA-Z0-9_-]*$/g,"").split(".");return{major:parseInt(t[0],10)||0,minor:parseInt(t[1],10)||0,patch:parseInt(t[2],10)||0,toString:function(){return this.major+"."+this.minor+"."+this.patch}}},toString:function(e){return e.major+"."+e.minor+"."+e.patch},toDocuVersion:function(e){return 0<=e.toLowerCase().indexOf("devel")||0<=e.toLowerCase().indexOf("rc")?"devel":e.substring(0,3)}},window.arangoHelper={alphabetColors:{a:"rgb(0,0,180)",b:"rgb(175,13,102)",c:"rgb(146,248,70)",d:"rgb(255,200,47)",e:"rgb(255,118,0)",f:"rgb(185,185,185)",g:"rgb(235,235,222)",h:"rgb(100,100,100)",i:"rgb(255,255,0)",j:"rgb(55,19,112)",k:"rgb(255,255,150)",l:"rgb(202,62,94)",m:"rgb(205,145,63)",n:"rgb(12,75,100)",o:"rgb(255,0,0)",p:"rgb(175,155,50)",q:"rgb(0,0,0)",r:"rgb(37,70,25)",s:"rgb(121,33,135)",t:"rgb(83,140,208)",u:"rgb(0,154,37)",v:"rgb(178,220,205)",w:"rgb(255,152,213)",x:"rgb(0,0,74)",y:"rgb(175,200,74)",z:"rgb(63,25,12)"},statusColors:{fatal:"#ad5148",info:"rgb(88, 214, 141)",error:"rgb(236, 112, 99)",warning:"#ffb075",debug:"rgb(64, 74, 83)"},getCurrentJwt:function(){return sessionStorage.getItem("jwt")},getCurrentJwtUsername:function(){return sessionStorage.getItem("jwtUser")},setCurrentJwt:function(e,t){sessionStorage.setItem("jwt",e),sessionStorage.setItem("jwtUser",t)},checkJwt:function(){$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/version"),contentType:"application/json",processData:!1,async:!0,error:function(e){401===e.status&&window.App.navigate("login",{trigger:!0})}})},getCoordinatorShortName:function(i){var n;return window.clusterHealth&&_.each(window.clusterHealth,function(e,t){i===t&&(n=e.ShortName)}),arangoHelper.escapeHtml(n)},getDatabaseShortName:function(e){return this.getCoordinatorShortName(e)},getDatabaseServerId:function(i){var n;return window.clusterHealth&&_.each(window.clusterHealth,function(e,t){i===e.ShortName&&(n=t)}),n},lastNotificationMessage:null,CollectionTypes:{},systemAttributes:function(){return{_id:!0,_rev:!0,_key:!0,_bidirectional:!0,_vertices:!0,_from:!0,_to:!0,$id:!0}},getCurrentSub:function(){return window.App.naviView.activeSubMenu},parseError:function(e,t){var i;try{i=JSON.parse(t.responseText).errorMessage}catch(e){i=e}this.arangoError(e,i)},setCheckboxStatus:function(e){_.each($(e).find("ul").find("li"),function(e){$(e).hasClass("nav-header")||($(e).find("input").attr("checked")?$(e).find("i").hasClass("css-round-label")?($(e).find("i").removeClass("fa-circle-o"),$(e).find("i").addClass("fa-dot-circle-o")):($(e).find("i").removeClass("fa-square-o"),$(e).find("i").addClass("fa-check-square-o")):$(e).find("i").hasClass("css-round-label")?($(e).find("i").removeClass("fa-dot-circle-o"),$(e).find("i").addClass("fa-circle-o")):($(e).find("i").removeClass("fa-check-square-o"),$(e).find("i").addClass("fa-square-o")))})},parseInput:function(e){var t,i=$(e).val();try{t=JSON.parse(i)}catch(e){t=i}return t},calculateCenterDivHeight:function(){var e=$(".navbar").height(),t=$(".footer").height();return $(window).height()-t-e-110},createTooltips:function(e,t){var i=this,n={arrow:!0,multiple:!1,content:function(e){var t=e.getAttribute("title");return e.removeAttribute("title"),t}};if(t&&(n.placement=t),"object"==typeof(e=e||".tippy"))_.each(e,function(e){i.lastTooltips=new tippy(e,n)});else{if(-1'+t+""),e.disabled||$("#subNavigationBar .bottom").children().last().bind("click",function(){window.App.navigate(e.route,{trigger:!0})})})},buildUserSubNav:function(e,t){var i={General:{route:"#user/"+encodeURIComponent(e)},Permissions:{route:"#user/"+encodeURIComponent(e)+"/permission"}};i[t].active=!0,this.buildSubNavBar(i)},buildGraphSubNav:function(e,t){var i={Content:{route:"#graph/"+encodeURIComponent(e)},Settings:{route:"#graph/"+encodeURIComponent(e)+"/settings"}};i[t].active=!0,this.buildSubNavBar(i)},buildNodeSubNav:function(e,t,i){var n={Dashboard:{route:"#node/"+encodeURIComponent(e)}};n[t].active=!0,n[i].disabled=!0,this.buildSubNavBar(n)},buildNodesSubNav:function(e,t){var i={Overview:{route:"#nodes"},Shards:{route:"#shards"}};i[e].active=!0,t&&(i[t].disabled=!0),this.buildSubNavBar(i)},buildServicesSubNav:function(e,t){var i={Store:{route:"#services/install"},Upload:{route:"#services/install/upload"},New:{route:"#services/install/new"},GitHub:{route:"#services/install/github"},Remote:{route:"#services/install/remote"}};frontendConfig.foxxStoreEnabled||delete i.Store,i[e].active=!0,t&&(i[t].disabled=!0),this.buildSubNavBar(i)},scaleability:void 0,buildCollectionSubNav:function(e,t){var i={Content:{route:"#collection/"+encodeURIComponent(e)+"/documents/1"},Indexes:{route:"#cIndices/"+encodeURIComponent(e)},Info:{route:"#cInfo/"+encodeURIComponent(e)},Settings:{route:"#cSettings/"+encodeURIComponent(e)}};i[t].active=!0,this.buildSubNavBar(i)},enableKeyboardHotkeys:function(e){var t=window.arangoHelper.hotkeysFunctions;!0===e&&($(document).on("keydown",null,"j",t.scrollDown),$(document).on("keydown",null,"k",t.scrollUp))},databaseAllowed:function(i){var e=function(e,t){e?arangoHelper.arangoError("",""):$.ajax({type:"GET",cache:!1,url:this.databaseUrl("/_api/database/",t),contentType:"application/json",processData:!1,success:function(){i(!1,!0)},error:function(){i(!0,!1)}})}.bind(this);this.currentDatabase(e)},arangoNotification:function(e,t,i){window.App.notificationList.add({title:e,content:t,info:i,type:"success"})},arangoError:function(e,t,i){$("#offlinePlaceholder").is(":visible")||window.App.notificationList.add({title:e,content:t,info:i,type:"error"})},arangoWarning:function(e,t,i){window.App.notificationList.add({title:e,content:t,info:i,type:"warning"})},arangoMessage:function(e,t,i){window.App.notificationList.add({title:e,content:t,info:i,type:"message"})},hideArangoNotifications:function(){$.noty.clearQueue(),$.noty.closeAll()},openDocEditor:function(e,t,i){var n=e.split("/"),o=this,a=new window.DocumentView({collection:window.App.arangoDocumentStore});a.breadcrumb=function(){},a.colid=n[0],a.docid=n[1],a.el=".arangoFrame .innerDiv",a.render(),a.setType(t),$(".arangoFrame .headerBar").remove(),$(".arangoFrame .outerDiv").prepend(''),$(".arangoFrame .outerDiv").click(function(){o.closeDocEditor()}),$(".arangoFrame .innerDiv").click(function(e){e.stopPropagation()}),$(".fa-times").click(function(){o.closeDocEditor()}),$(".arangoFrame").show(),a.customView=!0,a.customDeleteFunction=function(){window.modalView.hide(),$(".arangoFrame").hide()},a.customSaveFunction=function(e){o.closeDocEditor(),i&&i(e)},$(".arangoFrame #deleteDocumentButton").click(function(){a.deleteDocumentModal()}),$(".arangoFrame #saveDocumentButton").click(function(){a.saveDocument()}),$(".arangoFrame #deleteDocumentButton").css("display","none")},closeDocEditor:function(){$(".arangoFrame .outerDiv .fa-times").remove(),$(".arangoFrame").hide()},addAardvarkJob:function(e,t){$.ajax({cache:!1,type:"POST",url:this.databaseUrl("/_admin/aardvark/job"),data:JSON.stringify(e),contentType:"application/json",processData:!1,success:function(e){t&&t(!1,e)},error:function(e){t&&t(!0,e)}})},deleteAardvarkJob:function(e,t){$.ajax({cache:!1,type:"DELETE",url:this.databaseUrl("/_admin/aardvark/job/"+encodeURIComponent(e)),contentType:"application/json",processData:!1,success:function(e){t&&t(!1,e)},error:function(e){t&&t(!0,e)}})},deleteAllAardvarkJobs:function(t){$.ajax({cache:!1,type:"DELETE",url:this.databaseUrl("/_admin/aardvark/job"),contentType:"application/json",processData:!1,success:function(e){t&&t(!1,e)},error:function(e){t&&t(!0,e)}})},getAardvarkJobs:function(t){$.ajax({cache:!1,type:"GET",url:this.databaseUrl("/_admin/aardvark/job"),contentType:"application/json",processData:!1,success:function(e){t&&t(!1,e)},error:function(e){t&&t(!0,e)}})},getPendingJobs:function(t){$.ajax({cache:!1,type:"GET",url:this.databaseUrl("/_api/job/pending"),contentType:"application/json",processData:!1,success:function(e){t(!1,e)},error:function(e){t(!0,e)}})},syncAndReturnUnfinishedAardvarkJobs:function(a,r){var e=function(e,t){if(e)r(!0);else{var i=function(e,n){if(e)arangoHelper.arangoError("","");else{var o=[];0/g,">").replace(/"/g,""").replace(/'/g,"'")},backendUrl:function(e){return frontendConfig.basePath+e},databaseUrl:function(e,t){if("/_db/"===e.substr(0,5))throw new Error("Calling databaseUrl with a databased url ("+e+") doesn't make any sense");return t||(t="_system",frontendConfig.db&&(t=frontendConfig.db)),this.backendUrl("/_db/"+encodeURIComponent(t)+e)},showAuthDialog:function(){var e=!0;return"false"===localStorage.getItem("authenticationNotification")&&(e=!1),e},doNotShowAgain:function(){localStorage.setItem("authenticationNotification",!1)},renderEmpty:function(e,t){t?$("#content").html('
'+e+'
'):$("#content").html('
'+e+"
")},initSigma:function(){try{sigma.classes.graph.addMethod("neighbors",function(e){var t,i={},n=this.allNeighborsIndex[e]||{};for(t in n)i[t]=this.nodesIndex[t];return i}),sigma.classes.graph.addMethod("getNodeEdges",function(t){var e=this.edges(),i=[];return _.each(e,function(e){e.source!==t&&e.target!==t||i.push(e.id)}),i}),sigma.classes.graph.addMethod("getNodeEdgesCount",function(e){return this.allNeighborsCount[e]}),sigma.classes.graph.addMethod("getNodesCount",function(){return this.nodesArray.length})}catch(e){}},downloadLocalBlob:function(e,t){var i;if("csv"===t&&(i="text/csv; charset=utf-8"),"json"===t&&(i="application/json; charset=utf-8"),i){var n=new Blob([e],{type:i}),o=window.URL.createObjectURL(n),a=document.createElement("a");document.body.appendChild(a),a.style="display: none",a.href=o,a.download="results-"+window.frontendConfig.db+"."+t,a.click(),window.setTimeout(function(){window.URL.revokeObjectURL(o),document.body.removeChild(a)},500)}},download:function(e,r){$.ajax(e).success(function(e,t,i){if(r)r(e);else{var n=new Blob([JSON.stringify(e)],{type:i.getResponseHeader("Content-Type")||"application/octet-stream"}),o=window.URL.createObjectURL(n),a=document.createElement("a");document.body.appendChild(a),a.style="display: none",a.href=o,a.download=i.getResponseHeader("Content-Disposition").replace(/.* filename="([^")]*)"/,"$1"),a.click(),window.setTimeout(function(){window.URL.revokeObjectURL(o),document.body.removeChild(a)},500)}})},downloadPost:function(e,t,i,n){var o=new XMLHttpRequest;o.onreadystatechange=function(){if(4===this.readyState&&200===this.status){i&&i();var e=document.createElement("a");e.download=this.getResponseHeader("Content-Disposition").replace(/.* filename="([^")]*)"/,"$1"),document.body.appendChild(e);var t=window.URL.createObjectURL(this.response);e.href=t,e.click(),window.setTimeout(function(){window.URL.revokeObjectURL(t),document.body.removeChild(e)},500)}else 4===this.readyState&&void 0!==n&&n(this.status,this.statusText)},o.open("POST",e),window.arangoHelper.getCurrentJwt()&&o.setRequestHeader("Authorization","bearer "+window.arangoHelper.getCurrentJwt()),o.responseType="blob",o.send(t)},checkCollectionPermissions:function(e,t){var i=arangoHelper.databaseUrl("/_api/user/"+encodeURIComponent(window.App.userCollection.activeUser)+"/database/"+encodeURIComponent(frontendConfig.db)+"/"+encodeURIComponent(e));$.ajax({type:"GET",url:i,contentType:"application/json",success:function(e){"ro"===e.result&&t()},error:function(e){arangoHelper.arangoError("User","Could not fetch collection permissions.")}})},checkDatabasePermissions:function(t,i){var e=arangoHelper.databaseUrl("/_api/user/"+encodeURIComponent(window.App.userCollection.activeUser)+"/database/"+encodeURIComponent(frontendConfig.db));$.ajax({type:"GET",url:e,contentType:"application/json",success:function(e){"ro"===e.result?t&&t(!0):"rw"===e.result?i&&i(!1):"none"===e.result&&(frontendConfig.authenticationEnabled||i&&i(!1))},error:function(e){arangoHelper.arangoError("User","Could not fetch collection permissions.")}})},getFoxxFlag:function(){var e;return $("#new-app-replace").prop("checked")?e=!0:$("#new-app-teardown").prop("checked")&&(e=!1),e},createMountPointModal:function(e,t,i){var n,o=[],a=[];window.App.replaceApp&&(n=(n=window.App.replaceAppData.mount).substr(1,n.length)),a.push(window.modalView.createTextEntry("new-app-mount","Mount point",n,"The path the app will be mounted. Is not allowed to start with _","mountpoint",!1,[{rule:Joi.string().required(),msg:""}])),a.push(window.modalView.createCheckboxEntry("new-app-teardown","Run setup?",!0,"Should this app's setup script be executed after installing the app?",!0)),window.App.replaceApp?(a.push(window.modalView.createCheckboxEntry("new-app-replace","Discard configuration and dependency files?",!0,"Should this service's existing configuration and settings be removed completely before replacing the service?",!1)),o.push(window.modalView.createSuccessButton("Replace",e))):o.push(window.modalView.createSuccessButton("Install",e));var r="Create Foxx Service";window.App.replaceApp&&(r="Replace Foxx Service ("+window.App.replaceAppData.mount+")"),window.modalView.show("modalTable.ejs",r,o,a),window.App.replaceApp?($("#new-app-mount").attr("disabled","true"),$("#new-app-replace").attr("checked",!1),$("#new-app-replace").on("click",function(){$("#new-app-replace").prop("checked")?$("#new-app-teardown").attr("disabled",!0):$("#new-app-teardown").attr("disabled",!1)})):window.modalView.modalBindValidation({id:"new-app-mount",validateInput:function(){return[{rule:Joi.string().regex(/(\/|^)APP(\/|$)/i,{invert:!0}),msg:"May not contain APP"},{rule:Joi.string().regex(/^([a-zA-Z0-9_\-/]+)+$/),msg:"Can only contain [a-zA-Z0-9_-/]"},{rule:Joi.string().regex(/([^_]|_open\/)/),msg:"Mountpoints with _ are reserved for internal use"},{rule:Joi.string().regex(/[^/]$/),msg:"May not end with /"},{rule:Joi.string().required().min(1),msg:"Has to be non-empty"}]}})}}}(),function(){"use strict";if(!window.hasOwnProperty("TEST_BUILD")){window.templateEngine=new function(){var e={createTemplate:function(t){$("#"+t.replace(".","\\.")).html();return{render:function(e){return window.JST["templates/"+t](e)}}}};return e}}}(),function(){"use strict";window.dygraphConfig={defaultFrame:12e5,zeropad:function(e){return e<10?"0"+e:e},xAxisFormat:function(e){if(-1===e)return"";var t=new Date(e);return this.zeropad(t.getHours())+":"+this.zeropad(t.getMinutes())+":"+this.zeropad(t.getSeconds())},mergeObjects:function(n,o,e){var t,a={};return(e=e||[]).forEach(function(e){var t=n[e],i=o[e];void 0===t&&(t={}),void 0===i&&(i={}),a[e]=_.extend(t,i)}),t=_.extend(n,o),Object.keys(a).forEach(function(e){t[e]=a[e]}),t},mapStatToFigure:{pageFaults:["times","majorPageFaultsPerSecond","minorPageFaultsPerSecond"],systemUserTime:["times","systemTimePerSecond","userTimePerSecond"],totalTime:["times","avgQueueTime","avgRequestTime","avgIoTime"],dataTransfer:["times","bytesSentPerSecond","bytesReceivedPerSecond"],requests:["times","getsPerSecond","putsPerSecond","postsPerSecond","deletesPerSecond","patchesPerSecond","headsPerSecond","optionsPerSecond","othersPerSecond"]},colors:["rgb(95, 194, 135)","rgb(238, 190, 77)","#81ccd8","#7ca530","#3c3c3c","#aa90bd","#e1811d","#c7d4b2","#d0b2d4"],figureDependedOptions:{clusterRequestsPerSecond:{showLabelsOnHighlight:!0,title:"",header:"Cluster Requests per Second",stackedGraph:!0,div:"lineGraphLegend",labelsKMG2:!1,axes:{y:{valueFormatter:function(e){return parseFloat(e.toPrecision(3))},axisLabelFormatter:function(e){return 0===e?0:parseFloat(e.toPrecision(3))}}}},pageFaults:{header:"Page Faults",visibility:[!0,!1],labels:["datetime","Major Page","Minor Page"],div:"pageFaultsChart",labelsKMG2:!1,axes:{y:{valueFormatter:function(e){return parseFloat(e.toPrecision(3))},axisLabelFormatter:function(e){return 0===e?0:parseFloat(e.toPrecision(3))}}}},systemUserTime:{div:"systemUserTimeChart",header:"System and User Time",labels:["datetime","System Time","User Time"],stackedGraph:!0,labelsKMG2:!1,axes:{y:{valueFormatter:function(e){return parseFloat(e.toPrecision(3))},axisLabelFormatter:function(e){return 0===e?0:parseFloat(e.toPrecision(3))}}}},totalTime:{div:"totalTimeChart",header:"Total Time",labels:["datetime","Queue","Computation","I/O"],labelsKMG2:!1,axes:{y:{valueFormatter:function(e){return parseFloat(e.toPrecision(3))},axisLabelFormatter:function(e){return 0===e?0:parseFloat(e.toPrecision(3))}}},stackedGraph:!0},dataTransfer:{header:"Data Transfer",labels:["datetime","Bytes sent","Bytes received"],stackedGraph:!0,div:"dataTransferChart"},requests:{header:"Requests",labels:["datetime","Reads","Writes"],stackedGraph:!0,div:"requestsChart",axes:{y:{valueFormatter:function(e){return parseFloat(e.toPrecision(3))},axisLabelFormatter:function(e){return 0===e?0:parseFloat(e.toPrecision(3))}}}}},getDashBoardFigures:function(t){var i=[],n=this;return Object.keys(this.figureDependedOptions).forEach(function(e){"clusterRequestsPerSecond"!==e&&(n.figureDependedOptions[e].div||t)&&i.push(e)}),i},getDefaultConfig:function(e){var t=this,i={digitsAfterDecimal:1,drawGapPoints:!0,fillGraph:!0,fillAlpha:.85,showLabelsOnHighlight:!1,strokeWidth:0,lineWidth:0,strokeBorderWidth:0,includeZero:!0,highlightCircleSize:2.5,labelsSeparateLines:!0,strokeBorderColor:"rgba(0,0,0,0)",interactionModel:{},maxNumberWidth:10,colors:[this.colors[0]],xAxisLabelWidth:"50",rightGap:15,showRangeSelector:!1,rangeSelectorHeight:50,rangeSelectorPlotStrokeColor:"#365300",rangeSelectorPlotFillColor:"",pixelsPerLabel:50,labelsKMG2:!0,dateWindow:[(new Date).getTime()-this.defaultFrame,(new Date).getTime()],axes:{x:{valueFormatter:function(e){return t.xAxisFormat(e)}},y:{ticker:Dygraph.numericLinearTicks}}};return this.figureDependedOptions[e]&&(i=this.mergeObjects(i,this.figureDependedOptions[e],["axes"])).div&&i.labels&&(i.colors=this.getColors(i.labels),i.labelsDiv=document.getElementById(i.div+"Legend"),i.legend="always",i.showLabelsOnHighlight=!0),i},getDetailChartConfig:function(e){var t=_.extend(this.getDefaultConfig(e),{showRangeSelector:!0,interactionModel:null,showLabelsOnHighlight:!0,highlightCircleSize:2.5,legend:"always",labelsDiv:"div#detailLegend.dashboard-legend-inner"});return"pageFaults"===e&&(t.visibility=[!0,!0]),t.labels||(t.labels=["datetime",t.header],t.colors=this.getColors(t.labels)),t},getColors:function(e){return this.colors.concat([]).slice(0,e.length-1)}}}(),function(){"use strict";window.arangoCollectionModel=Backbone.Model.extend({idAttribute:"name",urlRoot:arangoHelper.databaseUrl("/_api/collection"),defaults:{id:"",name:"",status:"",type:"",isSystem:!1,picture:"",locked:!1,desc:void 0},getProperties:function(t){$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/collection/"+encodeURIComponent(this.get("id"))+"/properties"),contentType:"application/json",processData:!1,success:function(e){t(!1,e)},error:function(e){t(!0,e)}})},getFigures:function(t){$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/collection/"+this.get("id")+"/figures"),contentType:"application/json",processData:!1,success:function(e){t(!1,e)},error:function(){t(!0)}})},getRevision:function(t,i){$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/collection/"+this.get("id")+"/revision"),contentType:"application/json",processData:!1,success:function(e){t(!1,e,i)},error:function(){t(!0)}})},getIndex:function(t){var i=this;$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/index/?collection="+this.get("id")),contentType:"application/json",processData:!1,success:function(e){t(!1,e,i.get("id"))},error:function(e){t(!0,e,i.get("id"))}})},createIndex:function(e,n){var o=this;$.ajax({cache:!1,type:"POST",url:arangoHelper.databaseUrl("/_api/index?collection="+o.get("id")),headers:{"x-arango-async":"store"},data:JSON.stringify(e),contentType:"application/json",processData:!1,success:function(e,t,i){i.getResponseHeader("x-arango-async-id")?(window.arangoHelper.addAardvarkJob({id:i.getResponseHeader("x-arango-async-id"),type:"index",desc:"Creating Index",collection:o.get("id")}),n(!1,e)):n(!0,e)},error:function(e){n(!0,e)}})},deleteIndex:function(e,n){var o=this;$.ajax({cache:!1,type:"DELETE",url:arangoHelper.databaseUrl("/_api/index/"+this.get("name")+"/"+encodeURIComponent(e)),headers:{"x-arango-async":"store"},success:function(e,t,i){i.getResponseHeader("x-arango-async-id")?(window.arangoHelper.addAardvarkJob({id:i.getResponseHeader("x-arango-async-id"),type:"index",desc:"Removing Index",collection:o.get("id")}),n(!1,e)):n(!0,e)},error:function(e){n(!0,e)}}),n()},truncateCollection:function(){var e=this;$.ajax({cache:!1,type:"PUT",url:arangoHelper.databaseUrl("/_api/collection/"+this.get("id")+"/truncate"),success:function(){arangoHelper.arangoNotification("Collection truncated."),$.ajax({cache:!1,type:"PUT",url:arangoHelper.databaseUrl("/_admin/wal/flush?waitForSync=true&waitForCollector=true"),success:function(){$.ajax({cache:!1,type:"PUT",url:arangoHelper.databaseUrl("/_api/collection/"+e.get("id")+"/rotate"),success:function(){},error:function(){}})},error:function(){}})},error:function(e){arangoHelper.arangoError("Collection error: "+e.responseJSON.errorMessage)}})},warmupCollection:function(){$.ajax({cache:!1,type:"PUT",url:arangoHelper.databaseUrl("/_api/collection/"+this.get("id")+"/loadIndexesIntoMemory"),success:function(){arangoHelper.arangoNotification("Loading indexes into memory.")},error:function(e){arangoHelper.arangoError("Collection error: "+e.responseJSON.errorMessage)}})},loadCollection:function(e){$.ajax({cache:!1,type:"PUT",url:arangoHelper.databaseUrl("/_api/collection/"+this.get("id")+"/load"),success:function(){e(!1)},error:function(){e(!0)}}),e()},unloadCollection:function(e){$.ajax({cache:!1,type:"PUT",url:arangoHelper.databaseUrl("/_api/collection/"+this.get("id")+"/unload?flush=true"),success:function(){e(!1)},error:function(){e(!0)}}),e()},renameCollection:function(e,t){var i=this;$.ajax({cache:!1,type:"PUT",url:arangoHelper.databaseUrl("/_api/collection/"+this.get("id")+"/rename"),data:JSON.stringify({name:e}),contentType:"application/json",processData:!1,success:function(){i.set("name",e),t(!1)},error:function(e){t(!0,e)}})},changeCollection:function(e,t,i,n,o,a){"true"===e?e=!0:"false"===e&&(e=!1);var r={waitForSync:e,journalSize:parseInt(t,10),indexBuckets:parseInt(i,10)};return n&&(r.replicationFactor=parseInt(n,10)),o&&(r.minReplicationFactor=parseInt(o,10)),$.ajax({cache:!1,type:"PUT",url:arangoHelper.databaseUrl("/_api/collection/"+this.get("id")+"/properties"),data:JSON.stringify(r),contentType:"application/json",processData:!1,success:function(){a(!1)},error:function(e){a(!0,e)}}),!1}})}(),window.DatabaseModel=Backbone.Model.extend({idAttribute:"name",initialize:function(){},isNew:function(){"use strict";return!1},sync:function(e,t,i){"use strict";return"update"===e&&(e="create"),Backbone.sync(e,t,i)},url:arangoHelper.databaseUrl("/_api/database"),defaults:{}}),window.arangoDocumentModel=Backbone.Model.extend({initialize:function(){},urlRoot:arangoHelper.databaseUrl("/_api/document"),defaults:{_id:"",_rev:"",_key:""},getSorted:function(){"use strict";var t=this,e=Object.keys(t.attributes).sort(function(e,t){var i=arangoHelper.isSystemAttribute(e);return i!==arangoHelper.isSystemAttribute(t)?i?-1:1:e=this.getLastPageNumber()&&null!==this.totalAmount?this.page=this.getLastPageNumber()-1:this.page=e<1?0:e-1},getLastPageNumber:function(){return Math.max(Math.ceil(this.totalAmount/this.pagesize),1)},getOffset:function(){return this.page*this.pagesize},getPageSize:function(){return this.pagesize},setPageSize:function(e){if("all"===e)this.pagesize="all";else try{e=parseInt(e,10),this.pagesize=e}catch(e){}},setToFirst:function(){this.page=0},setToLast:function(){this.setPage(this.getLastPageNumber())},setToPrev:function(){this.setPage(this.getPage()-1)},setToNext:function(){this.setPage(this.getPage()+1)},setTotal:function(e){this.totalAmount=e},getTotal:function(){return this.totalAmount},setTotalMinusOne:function(){this.totalAmount--}})}(),window.ClusterStatisticsCollection=Backbone.Collection.extend({model:window.Statistics,url:"/_admin/statistics",updateUrl:function(){this.url=window.App.getNewRoute(this.host)+this.url},initialize:function(e,t){this.host=t.host,window.App.registerForUpdate(this)}}),function(){"use strict";window.ArangoCollections=Backbone.Collection.extend({url:arangoHelper.databaseUrl("/_api/collection"),model:arangoCollectionModel,searchOptions:{searchPhrase:null,includeSystem:!1,includeDocument:!0,includeEdge:!0,includeLoaded:!0,includeUnloaded:!0,sortBy:"name",sortOrder:1},translateStatus:function(e){switch(e){case 0:return"corrupted";case 1:return"new born collection";case 2:return"unloaded";case 3:return"loaded";case 4:return"unloading";case 5:return"deleted";case 6:return"loading";default:return"unknown"}},translateTypePicture:function(e){var t="";switch(e){case"document":t+="fa-file-text-o";break;case"edge":t+="fa-share-alt";break;case"unknown":t+="fa-question";break;default:t+="fa-cogs"}return t},parse:function(e){var t=this;return _.each(e.result,function(e){e.isSystem=arangoHelper.isSystemCollection(e),e.type=arangoHelper.collectionType(e),e.status=t.translateStatus(e.status),e.picture=t.translateTypePicture(e.type)}),e.result},getPosition:function(e){var t,i=this.getFiltered(this.searchOptions),n=null,o=null;for(t=0;t
"),$("#subNavigationBar .breadcrumb").html(e)},openApp:function(){var e=function(e,t){e?arangoHelper.arangoError("DB","Could not get current database"):window.open(this.appUrl(t),this.model.get("title")).focus()}.bind(this);arangoHelper.currentDatabase(e)},deleteApp:function(){var e=[window.modalView.createDeleteButton("Delete",function(){var e={teardown:$("#app_delete_run_teardown").is(":checked")};this.model.destroy(e,function(e,t){e||!1!==t.error||(window.modalView.hide(),window.App.navigate("services",{trigger:!0}))})}.bind(this))],t=[window.modalView.createCheckboxEntry("app_delete_run_teardown","Run teardown?",!0,"Should this app's teardown script be executed before removing the app?",!0)];window.modalView.show("modalTable.ejs",'Delete Foxx App mounted at "'+this.model.get("mount")+'"',e,t,void 0,"
'),$("#subNavigationBar .breadcrumb").html()},events:{"click #collectionPrev":"prevCollection","click #collectionNext":"nextCollection","click #filterCollection":"filterCollection","click #markDocuments":"editDocuments","click #importCollection":"importCollection","click #exportCollection":"exportCollection","click #filterSend":"sendFilter","click #addFilterItem":"addFilterItem","click .removeFilterItem":"removeFilterItem","click #deleteSelected":"deleteSelectedDocs","click #moveSelected":"moveSelectedDocs","click #addDocumentButton":"addDocumentModal","click #documents_first":"firstDocuments","click #documents_last":"lastDocuments","click #documents_prev":"prevDocuments","click #documents_next":"nextDocuments","click #confirmDeleteBtn":"confirmDelete","click .key":"nop",keyup:"returnPressedHandler","keydown .queryline input":"filterValueKeydown","click #importModal":"showImportModal","click #resetView":"resetView","click #confirmDocImport":"startUpload","click #exportDocuments":"startDownload","change #documentSize":"setPagesize","change #docsSort":"setSorting"},showSpinner:function(){$(".upload-indicator").show()},hideSpinner:function(){$(".upload-indicator").hide()},showImportModal:function(){$("#docImportModal").modal("show")},hideImportModal:function(){$("#docImportModal").modal("hide")},setPagesize:function(){var e=$("#documentSize").find(":selected").val();this.collection.setPagesize(e),this.collection.getDocuments(this.getDocsCallback.bind(this))},setSorting:function(){var e=$("#docsSort").val();""!==e&&null!=e||(e="_key"),this.collection.setSort(e)},returnPressedHandler:function(e){13===e.keyCode&&$(e.target).is($("#docsSort"))&&this.collection.getDocuments(this.getDocsCallback.bind(this)),13===e.keyCode&&!1===$("#confirmDeleteBtn").attr("disabled")&&this.confirmDelete()},nop:function(e){e.stopPropagation()},resetView:function(){$("input").val(""),$("select").val("=="),this.removeAllFilterItems(),$("#documentSize").val(this.collection.getPageSize()),$("#documents_last").css("visibility","visible"),$("#documents_first").css("visibility","visible"),this.addDocumentSwitch=!0,this.collection.resetFilter(),this.collection.loadTotal(function(e){e&&arangoHelper.arangoError("Document","Could not fetch documents count")}),this.restoredFilters=[],this.allowUpload=!1,this.files=void 0,this.file=void 0,$("#confirmDocImport").attr("disabled",!0),this.markFilterToggle(),this.collection.getDocuments(this.getDocsCallback.bind(this))},startDownload:function(){var e=this.collection.buildDownloadDocumentQuery();if(""!==e||void 0!==e||null!==e){var t="query/result/download/"+btoa(JSON.stringify(e));arangoHelper.download(t)}else arangoHelper.arangoError("Document error","could not download documents")},startUpload:function(){var e=function(e,t){e?arangoHelper.arangoError("Upload",t):(this.hideImportModal(),this.resetView()),this.hideSpinner()}.bind(this);!0===this.allowUpload&&(this.showSpinner(),this.collection.uploadDocuments(this.file,e))},uploadSetup:function(){var t=this;$("#importDocuments").change(function(e){t.files=e.target.files||e.dataTransfer.files,t.file=t.files[0],$("#confirmDocImport").attr("disabled",!1),t.allowUpload=!0})},buildCollectionLink:function(e){return"collection/"+encodeURIComponent(e.get("name"))+"/documents/1"},markFilterToggle:function(){0'),this.filters[e]=!0,this.checkFilterState()},filterValueKeydown:function(e){13===e.keyCode&&this.sendFilter()},checkFilterState:function(){if(1===$("#filterHeader .queryline").length)$("#filterHeader .removeFilterItem").remove();else if(0===$("#filterHeader .queryline").first().find(".removeFilterItem").length){var e=$("#filterHeader .queryline").first().children().first().attr("id"),t=e.substr(14,e.length);$("#filterHeader .queryline").first().find(".add-filter-item").after(' ')}0===$("#filterHeader .queryline").first().find(".add-filter-item").length&&$("#filterHeader .queryline").first().find(".filterValue").after('')},removeFilterItem:function(e){var t=e.currentTarget,i=t.id.replace(/^removeFilter/,"");delete this.filters[i],delete this.restoredFilters[i],$(t.parentElement).remove(),this.checkFilterState()},removeAllFilterItems:function(){var e,t=$("#filterHeader").children().length;for(e=1;e<=t;e++)$("#removeFilter"+e).parent().remove();this.filters={0:!0},this.filterId=0},addDocumentModal:function(e){if(!$(e.currentTarget).hasClass("disabled")){var t=window.location.hash.split("/")[1],i=[],n=[],o=function(e,t){e?arangoHelper.arangoError("Error","Could not fetch collection type"):"edge"===t?(n.push(window.modalView.createTextEntry("new-edge-from-attr","_from","","document _id: document handle of the linked vertex (incoming relation)",void 0,!1,[{rule:Joi.string().required(),msg:"No _from attribute given."}])),n.push(window.modalView.createTextEntry("new-edge-to","_to","","document _id: document handle of the linked vertex (outgoing relation)",void 0,!1,[{rule:Joi.string().required(),msg:"No _to attribute given."}])),n.push(window.modalView.createTextEntry("new-edge-key-attr","_key",void 0,"the edges unique key(optional attribute, leave empty for autogenerated key","is optional: leave empty for autogenerated key",!1,[{rule:Joi.string().allow("").optional(),msg:""}])),i.push(window.modalView.createSuccessButton("Create",this.addEdge.bind(this))),window.modalView.show("modalTable.ejs","Create edge",i,n)):(n.push(window.modalView.createTextEntry("new-document-key-attr","_key",void 0,"the documents unique key(optional attribute, leave empty for autogenerated key","is optional: leave empty for autogenerated key",!1,[{rule:Joi.string().allow("").optional(),msg:""}])),i.push(window.modalView.createSuccessButton("Create",this.addDocument.bind(this))),window.modalView.show("modalTable.ejs","Create document",i,n))}.bind(this);arangoHelper.collectionApiType(t,!0,o)}},addEdge:function(){function e(e,t,i){if(e)arangoHelper.arangoError("Error",i.errorMessage);else{window.modalView.hide(),t=t._id.split("/");try{n="collection/"+t[0]+"/"+t[1],decodeURI(n)}catch(e){n="collection/"+t[0]+"/"+encodeURIComponent(t[1])}window.location.hash=n}}var n,t=window.location.hash.split("/")[1],i=$(".modal-body #new-edge-from-attr").last().val(),o=$(".modal-body #new-edge-to").last().val(),a=$(".modal-body #new-edge-key-attr").last().val();""!==a||void 0!==a?this.documentStore.createTypeEdge(t,i,o,a,e):this.documentStore.createTypeEdge(t,i,o,null,e)},addDocument:function(){function e(e,t,i){if(e)arangoHelper.arangoError("Error",i.errorMessage);else{window.modalView.hide(),t=t.split("/");try{n="collection/"+t[0]+"/"+t[1],decodeURI(n)}catch(e){n="collection/"+t[0]+"/"+encodeURIComponent(t[1])}window.location.hash=n}}var n,t=window.location.hash.split("/")[1],i=$(".modal-body #new-document-key-attr").last().val();""!==i||void 0!==i?this.documentStore.createTypeDocument(t,i,e):this.documentStore.createTypeDocument(t,null,e)},moveSelectedDocs:function(){var e=[],t=[];0!==this.getSelectedDocs().length?(t.push(window.modalView.createTextEntry("move-documents-to","Move to","",!1,"collection-name",!0,[{rule:Joi.string().regex(/^[a-zA-Z]/),msg:"Collection name must always start with a letter."},{rule:Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),msg:'Only Symbols "_" and "-" are allowed.'},{rule:Joi.string().required(),msg:"No collection name given."}])),e.push(window.modalView.createSuccessButton("Move",this.confirmMoveSelectedDocs.bind(this))),window.modalView.show("modalTable.ejs","Move documents",e,t)):arangoHelper.arangoMessage("Move documents","No documents selected!")},confirmMoveSelectedDocs:function(){var e=this.getSelectedDocs(),t=this,i=$("#move-documents-to").val(),n=function(e){e?arangoHelper.arangoError("Error","Could not move document."):(t.collection.setTotalMinusOne(),this.collection.getDocuments(this.getDocsCallback.bind(this)),$("#markDocuments").click(),window.modalView.hide())}.bind(this);_.each(e,function(e){t.collection.moveDocument(e,t.collection.collectionID,i,n)})},deleteSelectedDocs:function(){var e=[],t=[],i=this.getSelectedDocs();0!==i.length?(t.push(window.modalView.createReadOnlyEntry(void 0,i.length+" documents selected","Do you want to delete all selected documents?",void 0,void 0,!1,void 0)),e.push(window.modalView.createDeleteButton("Delete",this.confirmDeleteSelectedDocs.bind(this))),window.modalView.show("modalTable.ejs","Delete documents",e,t)):arangoHelper.arangoMessage("Delete documents","No documents selected!")},confirmDeleteSelectedDocs:function(){var e=this.getSelectedDocs(),n=[],o=this;_.each(e,function(e){if("document"===o.type){var t=function(e){e?(n.push(!1),arangoHelper.arangoError("Document error","Could not delete document.")):(n.push(!0),o.collection.setTotalMinusOne(),o.collection.getDocuments(this.getDocsCallback.bind(this)),$("#markDocuments").click(),window.modalView.hide())}.bind(o);o.documentStore.deleteDocument(o.collection.collectionID,e,t)}else if("edge"===o.type){var i=function(e){e?(n.push(!1),arangoHelper.arangoError("Edge error","Could not delete edge")):(o.collection.setTotalMinusOne(),n.push(!0),o.collection.getDocuments(this.getDocsCallback.bind(this)),$("#markDocuments").click(),window.modalView.hide())}.bind(o);o.documentStore.deleteEdge(o.collection.collectionID,e,i)}})},getSelectedDocs:function(){var t=[];return _.each($("#docPureTable .pure-table-body .pure-table-row"),function(e){$(e).hasClass("selected-row")&&t.push($($(e).children()[1]).find(".key").text())}),t},remove:function(e){$(e.currentTarget).hasClass("disabled")||(this.docid=$(e.currentTarget).parent().parent().prev().find(".key").text(),$("#confirmDeleteBtn").attr("disabled",!1),$("#docDeleteModal").modal("show"))},confirmDelete:function(){$("#confirmDeleteBtn").attr("disabled",!0),"source"!==window.location.hash.split("/")[3]&&this.reallyDelete()},reallyDelete:function(){if("document"===this.type){var e=function(e){e?arangoHelper.arangoError("Error","Could not delete document"):(this.collection.setTotalMinusOne(),this.collection.getDocuments(this.getDocsCallback.bind(this)),$("#docDeleteModal").modal("hide"))}.bind(this);this.documentStore.deleteDocument(this.collection.collectionID,this.docid,e)}else if("edge"===this.type){var t=function(e){e?arangoHelper.arangoError("Edge error","Could not delete edge"):(this.collection.setTotalMinusOne(),this.collection.getDocuments(this.getDocsCallback.bind(this)),$("#docDeleteModal").modal("hide"))}.bind(this);this.documentStore.deleteEdge(this.collection.collectionID,this.docid,t)}},editModeClick:function(e){var t=$(e.currentTarget);t.hasClass("selected-row")?t.removeClass("selected-row"):t.addClass("selected-row");var i=this.getSelectedDocs();$(".selectedCount").text(i.length),_.each(this.editButtons,function(e){0'),e=$("#totalDocuments")),"document"===this.type&&e.html(numeral(this.collection.getTotal()).format("0,0")+" doc(s)"),"edge"===this.type&&e.html(numeral(this.collection.getTotal()).format("0,0")+" edge(s)"),this.collection.getTotal()>this.collection.MAX_SORT?($("#docsSort").attr("disabled",!0),$("#docsSort").attr("placeholder","Sort limit reached (docs count)")):($("#docsSort").attr("disabled",!1),$("#docsSort").attr("placeholder","Sort by attribute"))},breadcrumb:function(){var e=this;window.App.naviView&&void 0!==$("#subNavigationBar .breadcrumb").html()?($("#subNavigationBar .breadcrumb").html("Collection: "+arangoHelper.escapeHtml(this.collectionName)),arangoHelper.buildCollectionSubNav(this.collectionName,"Content")):window.setTimeout(function(){e.breadcrumb()},100)}})}(),function(){"use strict";function l(e){var t=e.split("/");return"collection/"+encodeURIComponent(t[0])+"/"+encodeURIComponent(t[1])}window.DocumentView=Backbone.View.extend({el:"#content",readOnly:!1,colid:0,docid:0,customView:!1,defaultMode:"tree",template:templateEngine.createTemplate("documentView.ejs"),events:{"click #saveDocumentButton":"saveDocument","click #deleteDocumentButton":"deleteDocumentModal","click #confirmDeleteDocument":"deleteDocument","click #document-from":"navigateToDocument","click #document-to":"navigateToDocument","keydown #documentEditor .ace_editor":"keyPress","keyup .jsoneditor .search input":"checkSearchBox","click #addDocument":"addDocument"},remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},checkSearchBox:function(e){""===$(e.currentTarget).val()&&this.editor.expandAll()},initialize:function(){var e=localStorage.getItem("JSONEditorMode");e&&(this.defaultMode=e)},addDocument:function(e){this.readOnly||window.App.documentsView.addDocumentModal(e)},storeMode:function(e){localStorage.setItem("JSONEditorMode",e),this.defaultMode=e,this.editor.setMode(this.defaultMode)},keyPress:function(e){e.ctrlKey&&13===e.keyCode?(e.preventDefault(),this.saveDocument()):e.metaKey&&13===e.keyCode&&(e.preventDefault(),this.saveDocument())},editor:0,setType:function(){var n=this,e=function(e,t,i){e?(arangoHelper.arangoError("Error","Document not found."),n.renderNotFound(i)):(this.type=i,this.breadcrumb(),this.fillInfo(),this.fillEditor(),arangoHelper.checkCollectionPermissions(this.colid,this.changeViewToReadOnly.bind(this)))}.bind(this);this.collection.getDocument(this.colid,this.docid,e)},renderNotFound:function(e){$(".document-info-div").remove(),$(".headerButton").remove(),$(".document-content-div").html('
Error
Document not found. Requested ID was: "'+e+'".
')},deleteDocumentModal:function(){if(!this.readOnly){var e=[],t=[];t.push(window.modalView.createReadOnlyEntry("doc-delete-button","Confirm delete, document id is",this.type._id||this.docid,void 0,void 0,!1,/[<>&'"]/)),e.push(window.modalView.createDeleteButton("Delete",this.deleteDocument.bind(this))),window.modalView.show("modalTable.ejs","Delete Document",e,t)}},deleteDocument:function(){var t=function(){if(this.customView)this.customDeleteFunction&&this.customDeleteFunction();else{var e="collection/"+encodeURIComponent(this.colid)+"/documents/1";window.modalView.hide(),window.App.navigate(e,{trigger:!0})}}.bind(this);if(this.type._from&&this.type._to){this.collection.deleteEdge(this.colid,this.docid,function(e){e?arangoHelper.arangoError("Edge error","Could not delete edge"):t()})}else{this.collection.deleteDocument(this.colid,this.docid,function(e){e?arangoHelper.arangoError("Error","Could not delete document"):t()})}},navigateToDocument:function(e){var t=$(e.target).attr("documentLink"),i=(t.split("%").length-1)%3;decodeURIComponent(t)!==t&&0!=i&&(t=decodeURIComponent(t)),t&&window.App.navigate(t,{trigger:!0})},fillInfo:function(){var e=this.collection.first(),t=e.get("_id"),i=e.get("_key"),n=e.get("_rev"),o=e.get("_from"),a=e.get("_to");if($("#document-type").css("margin-left","10px"),$("#document-type").text("_id:"),$("#document-id").css("margin-left","0"),$("#document-id").text(t),$("#document-key").text(i),$("#document-rev").text(n),o&&a){var r=l(o),s=l(a);$("#document-from").text(o),$("#document-from").attr("documentLink",r),$("#document-to").text(a),$("#document-to").attr("documentLink",s)}else $(".edge-info-container").hide()},fillEditor:function(){var e=this.removeReadonlyKeys(this.collection.first().attributes);$(".disabledBread").last().text(this.collection.first().get("_key")),this.editor.set(e),$(".ace_content").attr("font-size","11pt")},jsonContentChanged:function(){this.enableSaveButton()},resize:function(){$("#documentEditor").height($(".centralRow").height()-300)},render:function(){$(this.el).html(this.template.render({})),$("#documentEditor").height($(".centralRow").height()-300),this.disableSaveButton();var t=this,e=document.getElementById("documentEditor"),i={onChange:function(){t.jsonContentChanged()},onModeChange:function(e){t.storeMode(e)},search:!0,mode:"tree",modes:["tree","code"],ace:window.ace};this.editor=new JSONEditor(e,i);var n=localStorage.getItem("JSONEditorMode");return"code"!==n&&"tree"!==n||(this.defaultMode=n),this.defaultMode&&this.editor.setMode(this.defaultMode),this},changeViewToReadOnly:function(){this.readOnly=!0,$(".breadcrumb").find("a").html($(".breadcrumb").find("a").html()+" (read-only)"),this.editor.setMode("view"),$(".jsoneditor-modes").hide(),$(".bottomButtonBar button").addClass("disabled"),$(".bottomButtonBar button").unbind("click"),$("#addDocument").addClass("disabled")},cleanupEditor:function(){this.editor&&this.editor.destroy()},removeReadonlyKeys:function(e){return _.omit(e,["_key","_id","_from","_to","_rev"])},saveDocument:function(){if(void 0===$("#saveDocumentButton").attr("disabled"))if("_"===this.collection.first().attributes._id.substr(0,1)){var e=[],t=[];t.push(window.modalView.createReadOnlyEntry("doc-save-system-button","Caution","You are modifying a system collection. Really continue?",void 0,void 0,!1,/[<>&'"]/)),e.push(window.modalView.createSuccessButton("Save",this.confirmSaveDocument.bind(this))),window.modalView.show("modalTable.ejs","Modify System Collection",e,t)}else this.confirmSaveDocument()},confirmSaveDocument:function(){var e,i=this;window.modalView.hide();try{e=this.editor.get()}catch(e){return this.errorConfirmation(e),void this.disableSaveButton()}if(e=JSON.stringify(e),"edge"===this.type||this.type._from){var t=function(e,t){e?arangoHelper.arangoError("Error",t.responseJSON.errorMessage):(this.successConfirmation(),this.disableSaveButton(),i.customView&&i.customSaveFunction&&i.customSaveFunction(t))}.bind(this);this.collection.saveEdge(this.colid,this.docid,$("#document-from").html(),$("#document-to").html(),e,t)}else{var n=function(e,t){e||t[0]&&t[0].error?t[0]&&t[0].error?arangoHelper.arangoError("Error",t[0].errorMessage):arangoHelper.arangoError("Error",t.responseJSON.errorMessage):(this.successConfirmation(),this.disableSaveButton(),i.customView&&i.customSaveFunction&&i.customSaveFunction(t))}.bind(this);this.collection.saveDocument(this.colid,this.docid,e,n)}},successConfirmation:function(){arangoHelper.arangoNotification("Document saved.")},errorConfirmation:function(e){arangoHelper.arangoError("Document editor: ",e)},enableSaveButton:function(){$("#saveDocumentButton").prop("disabled",!1),$("#saveDocumentButton").addClass("button-success"),$("#saveDocumentButton").removeClass("button-close")},disableSaveButton:function(){$("#saveDocumentButton").prop("disabled",!0),$("#saveDocumentButton").addClass("button-close"),$("#saveDocumentButton").removeClass("button-success")},breadcrumb:function(){var e=window.location.hash.split("/");$("#subNavigationBar .breadcrumb").html('Collection: '+e[1]+''+this.type.charAt(0).toUpperCase()+this.type.slice(1)+": "+e[2])},escaped:function(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}})}(),function(){"use strict";window.FilterSelectView=Backbone.View.extend({el:"#filterSelectDiv",filterOptionsEl:".filterOptions",initialize:function(e){this.name=e.name,this.options=e.options,this.position=e.position,this.callback=e.callback,this.multiple=e.multiple},template:templateEngine.createTemplate("filterSelect.ejs"),events:{"click .filterOptions .inactive":"changeState","click .filterOptions .active":"changeState","click #showAll":"showAll","click #closeFilter":"hide","keyup .filterInput input":"filter"},remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},changeState:function(e){var t=$(e.currentTarget).attr("name");$(e.currentTarget).hasClass("active")?(this.options[t].active=!1,$(e.currentTarget).removeClass("active").addClass("inactive"),$(e.currentTarget).find(".marked").css("visibility","hidden")):(this.options[t].active=!0,$(e.currentTarget).removeClass("inactive").addClass("active"),$(e.currentTarget).find(".marked").css("visibility","visible")),this.callback&&this.callback(this.options)},filter:function(){var t=$("#"+this.name+"-filter").val();_.each(this.options,function(e){-1 div").css("right",this.position.right+"px"),$("#filterSelectDiv > div").css("top",this.position.top+30),this.show(),$("#"+this.name+"-filter").focus()},show:function(){$(this.el).show()},hide:function(){$("#filterSelectDiv").unbind("click"),$(this.el).hide(),this.remove()}})}(),function(){"use strict";window.FooterView=Backbone.View.extend({el:"#footerBar",system:{},isOffline:!0,isOfflineCounter:0,firstLogin:!0,timer:15e3,lap:0,timerFunction:null,events:{"click .footer-center p":"showShortcutModal"},initialize:function(){var e=this;window.setInterval(function(){e.getVersion()},e.timer),e.getVersion(),window.VISIBLE=!0,document.addEventListener("visibilitychange",function(){window.VISIBLE=!window.VISIBLE}),$("#offlinePlaceholder button").on("click",function(){e.getVersion()}),window.setTimeout(function(){!0===window.frontendConfig.isCluster&&($(".health-state").css("cursor","pointer"),$(".health-state").on("click",function(){window.App.navigate("#nodes",{trigger:!0})}))},1e3)},template:templateEngine.createTemplate("footerView.ejs"),showServerStatus:function(e){window.App.isCluster?this.renderClusterState(e):!0===e?($("#healthStatus").removeClass("negative"),$("#healthStatus").addClass("positive"),$(".health-state").html("GOOD"),$(".health-icon").html(''),$("#offlinePlaceholder").hide()):($("#healthStatus").removeClass("positive"),$("#healthStatus").addClass("negative"),$(".health-state").html("UNKNOWN"),$(".health-icon").html(''),window.modalView.hide(),$("#offlinePlaceholder").show(),$.noty.clearQueue(),$.noty.closeAll(),this.reconnectAnimation(0))},reconnectAnimation:function(e){var t=this;0===e&&(t.lap=e,$("#offlineSeconds").text(t.timer/1e3),clearTimeout(t.timerFunction)),t.lap')):($("#healthStatus").removeClass("negative"),$("#healthStatus").addClass("positive"),$(".health-state").html("NODES OK"),$(".health-icon").html(''))):($(".health-state").html("HEALTH ERROR"),$("#healthStatus").removeClass("positive"),$("#healthStatus").addClass("negative"),$(".health-icon").html(''))}(e)}})}else $("#healthStatus").removeClass("positive"),$("#healthStatus").addClass("negative"),$(".health-state").html(window.location.host+" OFFLINE"),$(".health-icon").html(''),$("#offlinePlaceholder").show(),this.reconnectAnimation(0)},showShortcutModal:function(){window.arangoHelper.hotkeysFunctions.showHotkeysModal()},getVersion:function(){var n=this;$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/version"),contentType:"application/json",processData:!1,async:!0,success:function(e){frontendConfig.version=e,frontendConfig.version.hasOwnProperty("version")||(frontendConfig.version.version="N/A"),n.showServerStatus(!0),!0===n.isOffline&&(n.isOffline=!1,n.isOfflineCounter=0,n.firstLogin?n.firstLogin=!1:window.setTimeout(function(){n.showServerStatus(!0)},1e3),n.system.name=e.server,n.system.version=e.version,n.render())},error:function(e){401===e.status?(n.showServerStatus(!0),window.App.navigate("login",{trigger:!0})):(n.isOffline=!0,n.isOfflineCounter++,1<=n.isOfflineCounter&&n.showServerStatus(!1))}}),n.system.hasOwnProperty("database")||$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/database/current"),contentType:"application/json",processData:!1,async:!0,success:function(e){var t=e.result.name;n.system.database=t;var i=window.setInterval(function(){$("#databaseNavi")&&(window.clearTimeout(i),i=null,n.render())},50)}})},renderVersion:function(){this.system.hasOwnProperty("database")&&this.system.hasOwnProperty("name")&&$(this.el).html(this.template.render({name:this.system.name,version:this.system.version,database:this.system.database}))},render:function(){return this.system.version||this.getVersion(),$(this.el).html(this.template.render({name:this.system.name,version:this.system.version})),this}})}(),function(){"use strict";window.FoxxActiveView=Backbone.View.extend({tagName:"div",className:"foxxTile tile pure-u-1-1 pure-u-sm-1-2 pure-u-md-1-3 pure-u-lg-1-4 pure-u-xl-1-5",template:templateEngine.createTemplate("foxxActiveView.ejs"),_show:!0,events:{click:"openAppDetailView"},openAppDetailView:function(){window.App.navigate("service/"+encodeURIComponent(this.model.get("mount")),{trigger:!0})},toggle:function(e,t){switch(e){case"devel":this.model.isDevelopment()&&(this._show=t);break;case"production":this.model.isDevelopment()||this.model.isSystem()||(this._show=t);break;case"system":this.model.isSystem()&&(this._show=t)}this._show?$(this.el).show():$(this.el).hide()},render:function(){return this.model.fetchThumbnail(function(){$(this.el).html(this.template.render({model:this.model}));var e=function(){this.model.needsConfiguration()&&(0<$(this.el).find(".warning-icons").length?$(this.el).find(".warning-icons").append(''):$(this.el).find("img").after(''))}.bind(this),t=function(){this.model.hasUnconfiguredDependencies()&&(0<$(this.el).find(".warning-icons").length?$(this.el).find(".warning-icons").append(''):$(this.el).find("img").after(''))}.bind(this);this.model.getConfiguration(e),this.model.getDependencies(t)}.bind(this)),$(this.el)}})}(),function(){"use strict";function e(e){this.collection=e.collection}function a(e){var t=this;if(!1===e.error)this.collection.fetch({success:function(){window.modalView.hide(),t.reload(),arangoHelper.arangoNotification("Services","Service "+e.name+" installed.")}});else{var i=e;switch(e.hasOwnProperty("responseJSON")&&(i=e.responseJSON),i.errorNum){case c.code:arangoHelper.arangoError("Services","Unable to download application from the given repository.");break;default:arangoHelper.arangoError("Services",i.errorNum+". "+i.errorMessage)}}}function i(){window.modalView.modalBindValidation({id:"new-app-mount",validateInput:function(){return[{rule:Joi.string().regex(/(\/|^)APP(\/|$)/i,{invert:!0}),msg:"May not contain /APP"},{rule:Joi.string().regex(/^(\/[a-zA-Z0-9_\-%]+)+$/),msg:"Can only contain [a-zA-Z0-9_-%]"},{rule:Joi.string().regex(/^\/([^_]|_open\/)/),msg:"Mountpoints with _ are reserved for internal use"},{rule:Joi.string().regex(/[^/]$/),msg:"May not end with /"},{rule:Joi.string().regex(/^\//),msg:"Has to start with /"},{rule:Joi.string().required().min(2),msg:"Has to be non-empty"}]}})}function n(){window.modalView.modalBindValidation({id:"new-app-author",validateInput:function(){return[{rule:Joi.string().required().min(1),msg:"Has to be non empty."}]}}),window.modalView.modalBindValidation({id:"new-app-name",validateInput:function(){return[{rule:Joi.string().required().regex(/^[a-zA-Z\-_][a-zA-Z0-9\-_]*$/),msg:"Can only contain a to z, A to Z, 0-9, '-' and '_'. Cannot start with a number."}]}}),window.modalView.modalBindValidation({id:"new-app-description",validateInput:function(){return[{rule:Joi.string().required().min(1),msg:"Has to be non empty."}]}}),window.modalView.modalBindValidation({id:"new-app-license",validateInput:function(){return[{rule:Joi.string().required().regex(/^[a-zA-Z0-9 .,;-]+$/),msg:"Can only contain a to z, A to Z, 0-9, '-', '.', ',' and ';'."}]}}),window.modalView.modalTestAll()}function r(e){window.modalView.clearValidators();var t=$("#modalButton1");switch(this._upgrade||i(),e){case"newApp":t.html("Generate"),t.prop("disabled",!1),n();break;case"appstore":t.html("Install"),t.prop("disabled",!0);break;case"github":window.modalView.modalBindValidation({id:"repository",validateInput:function(){return[{rule:Joi.string().required().regex(/^[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+$/),msg:"No valid Github account and repository."}]}}),t.html("Install"),t.prop("disabled",!1);break;case"zip":t.html("Install"),t.prop("disabled",!1)}t.prop("disabled")||window.modalView.modalTestAll()||t.prop("disabled",!0)}function s(e,t){var i,n,o;void 0===t?t=this._uploadData:this._uploadData=t,t&&window.modalView.modalTestAll()&&(this._upgrade?(i=this.mount,n=Boolean($("#new-app-teardown").prop("checked"))):i=window.arangoHelper.escapeHtml($("#new-app-mount").val()),o=Boolean($("#zip-app-islegacy").prop("checked")),this.collection.installFromZip(t.filename,i,a.bind(this),o,n))}function l(){switch($(".modal-body .tab-pane.active").attr("id")){case"newApp":(function(){if(window.modalView.modalTestAll()){var e,t;this._upgrade?(e=this.mount,t=$("#new-app-teardown").prop("checked")):e=window.arangoHelper.escapeHtml($("#new-app-mount").val());var i={name:window.arangoHelper.escapeHtml($("#new-app-name").val()),documentCollections:_.map($("#new-app-document-collections").select2("data"),function(e){return window.arangoHelper.escapeHtml(e.text)}),edgeCollections:_.map($("#new-app-edge-collections").select2("data"),function(e){return window.arangoHelper.escapeHtml(e.text)}),author:window.arangoHelper.escapeHtml($("#new-app-author").val()),license:window.arangoHelper.escapeHtml($("#new-app-license").val()),description:window.arangoHelper.escapeHtml($("#new-app-description").val())};this.collection.generate(i,e,a.bind(this),t)}}).apply(this);break;case"github":(function(){if(window.modalView.modalTestAll()){var e,t,i,n;this._upgrade?(t=this.mount,i=$("#new-app-teardown").prop("checked")):t=window.arangoHelper.escapeHtml($("#new-app-mount").val()),e=window.arangoHelper.escapeHtml($("#repository").val()),""===window.arangoHelper.escapeHtml($("#tag").val())&&"master";var o={url:window.arangoHelper.escapeHtml($("#repository").val()),version:window.arangoHelper.escapeHtml($("#tag").val())};try{Joi.assert(e,Joi.string().regex(/^[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+$/))}catch(e){return}n=Boolean($("#github-app-islegacy").prop("checked")),this.collection.installFromGithub(o,t,a.bind(this),n,i)}}).apply(this);break;case"zip":s.apply(this)}}function o(e,t){var i=[],n={"click #infoTab a":function(e){var t=$(e.currentTarget).attr("href").substr(1);r.call(this,t)}.bind(e),"click .install-app":function(e){if(r.call(this,"appstore"),window.modalView.modalTestAll()){var t,i;this._upgrade?(t=this.mount,i=$("#new-app-teardown").prop("checked")):t=window.arangoHelper.escapeHtml($("#new-app-mount").val());var n=$(e.currentTarget).attr("appId"),o=$(e.currentTarget).attr("appVersion");void 0!==i?this.collection.installFromStore({name:n,version:o},t,a.bind(this),i):this.collection.installFromStore({name:n,version:o},t,a.bind(this)),window.modalView.hide(),arangoHelper.arangoNotification("Services","Installing "+n+".")}}.bind(e)};function o(){var e=$("#modalButton1");e.prop("disabled")||window.modalView.modalTestAll()?e.prop("disabled",!1):e.prop("disabled",!0)}i.push(window.modalView.createSuccessButton("Generate",l.bind(e))),window.modalView.show("modalApplicationMount.ejs","Install Service",i,t,void 0,void 0,n),$("#new-app-document-collections").select2({tags:[],showSearchBox:!1,minimumResultsForSearch:-1,width:"336px"}),$("#new-app-edge-collections").select2({tags:[],showSearchBox:!1,minimumResultsForSearch:-1,width:"336px"}),$(".select2-search-field input").focusout(function(){o(),window.setTimeout(function(){$(".select2-drop").is(":visible")&&($("#select2-search-field input").is(":focus")||($("#s2id_new-app-document-collections").select2("close"),$("#s2id_new-app-edge-collections").select2("close"),o()))},200)}),$(".select2-search-field input").focusin(function(){$(".select2-drop").is(":visible")&&$("#modalButton1").prop("disabled",!0)}),$("#upload-foxx-zip").uploadFile({url:arangoHelper.databaseUrl("/_api/upload?multipart=true"),allowedTypes:"zip,js",multiple:!1,onSuccess:s.bind(e)}),$.get("foxxes/fishbowl",function(e){var t=$("#appstore-content");t.html(""),_.each(_.sortBy(e,"name"),function(e){t.append(d.render(e))})}).fail(function(){$("#appstore-content").append("
Store is not available. ArangoDB is not able to connect to github.com
')},calculateEdgeDefinitionMap:function(){var t={};return this.collection.models.forEach(function(e){e.get("edgeDefinitions").forEach(function(e){t[e.collection]={from:e.from,to:e.to}})}),t}})}(),function(){"use strict";window.GraphSettingsView=Backbone.View.extend({el:"#graphSettingsContent",remove:function(){return this.$el.empty().off(),this.stopListening(),this},general:{graph:{type:"divider",name:"Graph"},nodeStart:{type:"string",name:"Startnode",desc:"A valid node id or space seperated list of id's. If empty, a random node will be chosen.",value:2},layout:{type:"select",name:"Layout",desc:"Different graph algorithms. No overlap is very fast (more than 5000 nodes), force is slower (less than 5000 nodes) and fruchtermann is the slowest (less than 500 nodes).",noverlap:{name:"No overlap",val:"noverlap"},force:{name:"Force",val:"force"},fruchtermann:{name:"Fruchtermann",val:"fruchtermann"}},renderer:{type:"select",name:"Renderer",desc:"Canvas enables editing, WebGL is only for displaying a graph but much faster.",canvas:{name:"Canvas",val:"canvas"},webgl:{name:"WebGL (experimental)",val:"webgl"}},depth:{desc:"Search depth, starting from your start node.",type:"number",name:"Search Depth",value:2},limit:{desc:"Limit nodes count. If empty or zero, no limit is set.",type:"number",name:"Limit",value:250}},specific:{nodes:{type:"divider",name:"Nodes"},nodeLabel:{type:"string",name:"Label",desc:"Node label. Please choose a valid and available node attribute.",default:"_key"},nodeLabelByCollection:{type:"select",name:"Add Collection Name",desc:"Append collection name to the label?",yes:{name:"Yes",val:"true"},no:{name:"No",val:"false"}},nodeColorByCollection:{type:"select",name:"Color By Collections",no:{name:"No",val:"false"},yes:{name:"Yes",val:"true"},desc:"Should nodes be colorized by their collection? If enabled, node color and node color attribute will be ignored."},nodeColor:{type:"color",name:"Color",desc:"Default node color. RGB or HEX value.",default:"#2ecc71"},nodeColorAttribute:{type:"string",name:"Color Attribute",desc:"If an attribute is given, nodes will then be colorized by the attribute. This setting ignores default node color if set."},nodeSizeByEdges:{type:"select",name:"Size By Connections",yes:{name:"Yes",val:"true"},no:{name:"No",val:"false"},desc:"Should nodes be sized by their edges count? If enabled, node sizing attribute will be ignored."},nodeSize:{type:"string",name:"Sizing Attribute",desc:"Default node size. Numeric value > 0."},edges:{type:"divider",name:"Edges"},edgeLabel:{type:"string",name:"Label",desc:"Default edge label."},edgeLabelByCollection:{type:"select",name:"Add Collection Name",desc:"Set label text by collection. If activated edge label attribute will be ignored.",yes:{name:"Yes",val:"true"},no:{name:"No",val:"false"}},edgeColorByCollection:{type:"select",name:"Color By Collections",no:{name:"No",val:"false"},yes:{name:"Yes",val:"true"},desc:"Should edges be colorized by their collection? If enabled, edge color and edge color attribute will be ignored."},edgeColor:{type:"color",name:"Color",desc:"Default edge color. RGB or HEX value.",default:"#cccccc"},edgeColorAttribute:{type:"string",name:"Color Attribute",desc:"If an attribute is given, edges will then be colorized by the attribute. This setting ignores default edge color if set."},edgeEditable:{type:"select",hide:"true",name:"Editable",yes:{name:"Yes",val:"true"},no:{name:"No",val:"false"},desc:"Should edges be editable?"},edgeType:{type:"select",name:"Type",desc:"The type of the edge",line:{name:"Line",val:"line"},arrow:{name:"Arrow",val:"arrow"},curve:{name:"Curve",val:"curve"},dotted:{name:"Dotted",val:"dotted"},dashed:{name:"Dashed",val:"dashed"},tapered:{name:"Tapered",val:"tapered"}}},template:templateEngine.createTemplate("graphSettingsView.ejs"),initialize:function(e){this.name=e.name,this.userConfig=e.userConfig,this.saveCallback=e.saveCallback,e.noDefinedGraph&&(this.noDefinedGraph=e.noDefinedGraph)},events:{"click #saveGraphSettings":"saveGraphSettings","click #restoreGraphSettings":"setDefaults","keyup #graphSettingsView input":"checkEnterKey","keyup #graphSettingsView select":"checkEnterKey",'change input[type="range"]':"saveGraphSettings",'change input[type="color"]':"checkColor","change select":"saveGraphSettings","focus #graphSettingsView input":"lastFocus","focus #graphSettingsView select":"lastFocus",'focusout #graphSettingsView input[type="text"]':"checkinput"},lastFocus:function(e){this.lastFocussed=e.currentTarget.id,this.lastFocussedValue=$(e.currentTarget).val()},checkinput:function(e){500Fetching graph data. Please wait ... If it`s taking too much time to draw the graph, please navigate to: Graphs ViewClick the settings icon and reset the display settings.It is possible that the graph is too big to be handled by the browser.');function i(){var e={};n.graphConfig&&(delete(e=_.clone(n.graphConfig)).layout,delete e.edgeType,delete e.renderer),n.tmpStartNode&&(n.graphConfig?0===n.graphConfig.nodeStart.length&&(e.nodeStart=n.tmpStartNode):e.nodeStart=n.tmpStartNode),n.setupSigma(),n.fetchStarted=new Date,$.ajax({type:"GET",url:arangoHelper.databaseUrl("/_admin/aardvark/graph/"+encodeURIComponent(n.name)),contentType:"application/json",data:e,success:function(e){!0===e.empty?n.renderGraph(e,t):(e.settings&&e.settings.startVertex&&void 0===n.graphConfig.startNode&&void 0===n.tmpStartNode&&(n.tmpStartNode=e.settings.startVertex._id),n.fetchFinished=new Date,n.calcStart=n.fetchFinished,$("#calcText").html("Server response took "+Math.abs(n.fetchFinished.getTime()-n.fetchStarted.getTime())+" ms. Initializing graph engine. Please wait ... "),window.setTimeout(function(){n.renderGraph(e,t)},50))},error:function(e){try{var t;if(e.responseJSON.exception)if(t=e.responseJSON.exception,-1!==e.responseJSON.exception.search("1205")){var i='Starting point: '+n.graphConfig.nodeStart+" is invalid";$("#calculatingGraph").html('
'),r.startLayout();var p=250;e.nodes&&(p=e.nodes.length,i?p<250?p=250:p+=500:(p<=250&&(p=500),p+=500)),e.empty&&arangoHelper.arangoNotification("Graph","Your graph is empty. Click inside the white window to create your first node."),window.setTimeout(function(){r.stopLayout()},p)}else"fruchtermann"===r.algorithm&&sigma.layouts.fruchtermanReingold.start(c);"force"!==r.algorithm&&r.reInitDragListener(),document.getElementsByClassName("sigma-mouse")[0].addEventListener("mousemove",r.trackCursorPosition.bind(this),!1),t&&($("#"+t).focus(),$("#graphSettingsContent").animate({scrollTop:$("#"+t).offset().top},2e3)),$("#calculatingGraph").fadeOut("slow"),i||r.graphConfig&&r.graphConfig.nodeSizeByEdges,r.calcFinished=new Date,!0===e.empty&&$(".sigma-background").before('The graph is empty. Please right-click to add a node.'),!0===r.graphNotInitialized&&(r.updateColors(r.tmpGraphArray),r.graphNotInitialized=!1,r.tmpGraphArray=[]),"force"===r.algorithm?$("#toggleForce").fadeIn("fast"):$("#toggleForce").fadeOut("fast")},reInitDragListener:function(){var t=this;void 0!==this.dragListener&&(sigma.plugins.killDragNodes(this.currentGraph),this.dragListener={}),this.dragListener=sigma.plugins.dragNodes(this.currentGraph,this.currentGraph.renderers[0]),this.dragListener.bind("drag",function(e){t.dragging=!0}),this.dragListener.bind("drop",function(e){window.setTimeout(function(){t.dragging=!1},400)})},keyUpFunction:function(e){switch(e.keyCode){case 76:e.altKey&&this.toggleLasso()}},toggleLayout:function(){this.layouting?this.stopLayout():this.startLayout()},startLayout:function(e,t){var i=this;this.currentGraph.settings("drawLabels",!1),this.currentGraph.settings("drawEdgeLabels",!1),sigma.plugins.killDragNodes(this.currentGraph),!0===e&&(this.currentGraph.killForceAtlas2(),window.setTimeout(function(){i.stopLayout(),t&&i.currentGraph.refresh({skipIndexation:!0})},500)),$("#toggleForce .fa").removeClass("fa-play").addClass("fa-pause"),$("#toggleForce span").html("Stop layout"),this.layouting=!0,this.aqlMode,this.currentGraph.startForceAtlas2({worker:!0})},stopLayout:function(){$("#toggleForce .fa").removeClass("fa-pause").addClass("fa-play"),$("#toggleForce span").html("Resume layout"),this.layouting=!1,this.currentGraph.stopForceAtlas2(),this.currentGraph.settings("drawLabels",!0),this.currentGraph.settings("drawEdgeLabels",!0),this.currentGraph.refresh({skipIndexation:!0}),this.reInitDragListener()}})}(),function(){"use strict";window.HelpUsView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("helpUsView.ejs"),render:function(){this.$el.html(this.template.render({}))}})}(),function(){"use strict";window.IndicesView=Backbone.View.extend({el:"#content",initialize:function(e){var t=this;this.collectionName=e.collectionName,this.model=this.collection,t.interval=window.setInterval(function(){-1!==window.location.hash.indexOf("cIndices/"+t.collectionName)&&window.VISIBLE&&$("#collectionEditIndexTable").is(":visible")&&!$("#indexDeleteModal").is(":visible")&&t.rerender()},t.refreshRate)},interval:null,refreshRate:1e4,template:templateEngine.createTemplate("indicesView.ejs"),events:{},remove:function(){return this.interval&&window.clearInterval(this.interval),this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},render:function(){function t(e){var t=e.supports.aliases;t=t?t.indexes:{},$(i.el).html(i.template.render({model:i.model,supported:e.supports.indexes.filter(function(e){return!t.hasOwnProperty(e)})})),i.breadcrumb(),window.arangoHelper.buildCollectionSubNav(i.collectionName,"Indexes"),i.getIndex(),arangoHelper.checkCollectionPermissions(i.collectionName,i.changeViewToReadOnly)}var i=this;this.engineData?t(this.engineData):$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/engine"),contentType:"application/json",processData:!1,success:function(e){i.engineData=e,t(e)},error:function(){arangoHelper.arangoNotification("Index","Could not fetch index information.")}})},rerender:function(){this.getIndex(!0)},changeViewToReadOnly:function(){$(".breadcrumb").html($(".breadcrumb").html()+" (read-only)"),$("#addIndex").addClass("disabled"),$("#addIndex").css("color","rgba(0,0,0,.5)"),$("#addIndex").css("cursor","not-allowed")},breadcrumb:function(){$("#subNavigationBar .breadcrumb").html("Collection: "+this.collectionName)},getIndex:function(n){var e=function(e,t,i){e?window.arangoHelper.arangoError("Index",t.errorMessage):this.renderIndex(t,i,n)}.bind(this);this.model.getIndex(e)},createIndex:function(){var e,t,i,n,o,a,r=this,s={};switch($("#newIndexType").val()){case"Ttl":e=$("#newTtlFields").val();var l=parseInt($("#newTtlExpireAfter").val(),10)||0;o=r.checkboxToValue("#newTtlBackground"),a=$("#newTtlName").val(),s={type:"ttl",fields:r.stringToArray(e),expireAfter:l,inBackground:o,name:a};break;case"Geo":e=$("#newGeoFields").val(),o=r.checkboxToValue("#newGeoBackground");var c=r.checkboxToValue("#newGeoJson");a=$("#newGeoName").val(),s={type:"geo",fields:r.stringToArray(e),geoJson:c,inBackground:o,name:a};break;case"Persistent":e=$("#newPersistentFields").val(),t=r.checkboxToValue("#newPersistentUnique"),i=r.checkboxToValue("#newPersistentSparse"),n=r.checkboxToValue("#newPersistentDeduplicate"),o=r.checkboxToValue("#newPersistentBackground"),a=$("#newPersistentName").val(),s={type:"persistent",fields:r.stringToArray(e),unique:t,sparse:i,deduplicate:n,inBackground:o,name:a};break;case"Hash":e=$("#newHashFields").val(),t=r.checkboxToValue("#newHashUnique"),i=r.checkboxToValue("#newHashSparse"),n=r.checkboxToValue("#newHashDeduplicate"),o=r.checkboxToValue("#newHashBackground"),a=$("#newHashName").val(),s={type:"hash",fields:r.stringToArray(e),unique:t,sparse:i,deduplicate:n,inBackground:o,name:a};break;case"Fulltext":e=$("#newFulltextFields").val();var d=parseInt($("#newFulltextMinLength").val(),10)||0;o=r.checkboxToValue("#newFulltextBackground"),a=$("#newFulltextName").val(),s={type:"fulltext",fields:r.stringToArray(e),minLength:d,inBackground:o,name:a};break;case"Skiplist":e=$("#newSkiplistFields").val(),t=r.checkboxToValue("#newSkiplistUnique"),i=r.checkboxToValue("#newSkiplistSparse"),n=r.checkboxToValue("#newSkiplistDeduplicate"),o=r.checkboxToValue("#newSkiplistBackground"),a=$("#newSkiplistName").val(),s={type:"skiplist",fields:r.stringToArray(e),unique:t,sparse:i,deduplicate:n,inBackground:o,name:a}}this.model.createIndex(s,function(e,t){if(e)if(t){var i=JSON.parse(t.responseText);arangoHelper.arangoError("Index error",i.errorMessage)}else arangoHelper.arangoError("Index error","Could not create index.");else arangoHelper.arangoNotification("Index","Creation in progress. This may take a while.");r.toggleNewIndexView(),r.render()})},bindIndexEvents:function(){this.unbindIndexEvents();var t=this;$("#indexEditView #addIndex").bind("click",function(){t.toggleNewIndexView(),$("#cancelIndex").unbind("click"),$("#cancelIndex").bind("click",function(){t.toggleNewIndexView(),t.render()}),$("#createIndex").unbind("click"),$("#createIndex").bind("click",function(){t.createIndex()})}),$("#newIndexType").bind("change",function(){t.selectIndexType()}),$(".deleteIndex").bind("click",function(e){t.prepDeleteIndex(e)}),$("#infoTab a").bind("click",function(e){if($("#indexDeleteModal").remove(),"Indexes"!==$(e.currentTarget).html()||$(e.currentTarget).parent().hasClass("active")||($("#newIndexView").hide(),$("#indexEditView").show(),$("#indexHeaderContent #modal-dialog .modal-footer .button-danger").hide(),$("#indexHeaderContent #modal-dialog .modal-footer .button-success").hide(),$("#indexHeaderContent #modal-dialog .modal-footer .button-notification").hide()),"General"===$(e.currentTarget).html()&&!$(e.currentTarget).parent().hasClass("active")){$("#indexHeaderContent #modal-dialog .modal-footer .button-danger").show(),$("#indexHeaderContent #modal-dialog .modal-footer .button-success").show(),$("#indexHeaderContent #modal-dialog .modal-footer .button-notification").show();var t=$(".index-button-bar2")[0];$("#cancelIndex").is(":visible")&&($("#cancelIndex").detach().appendTo(t),$("#createIndex").detach().appendTo(t))}})},prepDeleteIndex:function(e){var t=this;this.lastTarget=e,this.lastId=$(this.lastTarget.currentTarget).parent().parent().first().children().first().text(),$("#indexDeleteModal").length||($("#content #modal-dialog .modal-footer").after('
Really delete?
'),$("#indexHeaderContent #indexConfirmDelete").unbind("click"),$("#indexHeaderContent #indexConfirmDelete").bind("click",function(){$("#indexHeaderContent #indexDeleteModal").remove(),t.deleteIndex()}),$("#indexHeaderContent #indexAbortDelete").unbind("click"),$("#indexHeaderContent #indexAbortDelete").bind("click",function(){$("#indexHeaderContent #indexDeleteModal").remove()}))},unbindIndexEvents:function(){$("#indexHeaderContent #indexEditView #addIndex").unbind("click"),$("#indexHeaderContent #newIndexType").unbind("change"),$("#indexHeaderContent #infoTab a").unbind("click"),$("#indexHeaderContent .deleteIndex").unbind("click")},deleteIndex:function(){var e=function(e){e?(arangoHelper.arangoError("Could not delete index"),$("tr th:contains('"+this.lastId+"')").parent().children().last().html(''),this.model.set("locked",!1)):e||void 0===e||($("tr th:contains('"+this.lastId+"')").parent().remove(),this.model.set("locked",!1))}.bind(this);this.model.set("locked",!0),this.model.deleteIndex(this.lastId,e),$("tr th:contains('"+this.lastId+"')").parent().children().last().html('')},renderIndex:function(e,i,t){this.index=e;arangoHelper.getAardvarkJobs(function(e,t){if(e)arangoHelper.arangoError("Jobs","Could not read pending jobs.");else{var o=function(e,t,i){e?404===t.responseJSON.code?arangoHelper.deleteAardvarkJob(i):400===t.responseJSON.code?(arangoHelper.arangoError("Index creation failed",t.responseJSON.errorMessage),arangoHelper.deleteAardvarkJob(i)):204===t.responseJSON.code&&arangoHelper.arangoMessage("Index","There is at least one new index in the queue or in the process of being created."):arangoHelper.deleteAardvarkJob(i)};_.each(t,function(n){n.collection===i&&$.ajax({type:"PUT",cache:!1,url:arangoHelper.databaseUrl("/_api/job/"+n.id),contentType:"application/json",success:function(e,t,i){o(!1,e,n.id)},error:function(e){o(!0,e,n.id)}})})}});var r="collectionInfoTh modal-text";if(this.index){var s="",l="";t&&$("#collectionEditIndexTable tbody").empty(),_.each(this.index.indexes,function(e){l="primary"===e.type||"edge"===e.type?'':'',void 0!==e.fields&&(s=e.fields.join(", "));var t=e.id.indexOf("/"),i=e.id.substr(t+1,e.id.length),n=e.hasOwnProperty("selectivityEstimate")?(100*e.selectivityEstimate).toFixed(2)+"%":"n/a",o=e.hasOwnProperty("sparse")?e.sparse:"n/a",a=e.hasOwnProperty("deduplicate")?e.deduplicate:"n/a";$("#collectionEditIndexTable").append("
"+arangoHelper.escapeHtml(i)+"
"+arangoHelper.escapeHtml(e.type)+"
"+arangoHelper.escapeHtml(e.unique)+"
"+arangoHelper.escapeHtml(o)+"
"+arangoHelper.escapeHtml(a)+"
"+arangoHelper.escapeHtml(n)+"
"+arangoHelper.escapeHtml(s)+"
"+arangoHelper.escapeHtml(e.name)+"
"+l+"
")})}this.bindIndexEvents()},selectIndexType:function(){$(".newIndexClass").hide();var e=$("#newIndexType").val();null===e&&(e=$("#newIndexType").children().first().attr("value"),$("#newIndexType").val(arangoHelper.escapeHtml(e))),$("#newIndexType"+e).show()},resetIndexForms:function(){$("#indexHeader input").val("").prop("checked",!1),$("#newIndexType").val("unknown").prop("selected",!0),this.selectIndexType()},toggleNewIndexView:function(){if(!$("#addIndex").hasClass("disabled")){var e=$(".index-button-bar2")[0];$("#indexEditView").is(":visible")?($("#indexEditView").hide(),$("#newIndexView").show(),$("#cancelIndex").detach().appendTo("#indexHeaderContent #modal-dialog .modal-footer"),$("#createIndex").detach().appendTo("#indexHeaderContent #modal-dialog .modal-footer")):($("#indexEditView").show(),$("#newIndexView").hide(),$("#cancelIndex").detach().appendTo(e),$("#createIndex").detach().appendTo(e)),this.resetIndexForms()}arangoHelper.createTooltips(".index-tooltip")},stringToArray:function(e){var t=[];return e.split(",").forEach(function(e){""!==(e=e.replace(/(^\s+|\s+$)/g,""))&&t.push(e)}),t},checkboxToValue:function(e){return $(e).prop("checked")}})}(),function(){"use strict";window.InfoView=Backbone.View.extend({el:"#content",initialize:function(e){this.collectionName=e.collectionName,this.model=this.collection},events:{},render:function(){this.breadcrumb(),window.arangoHelper.buildCollectionSubNav(this.collectionName,"Info"),this.renderInfoView(),arangoHelper.checkCollectionPermissions(this.collectionName,this.changeViewToReadOnly)},changeViewToReadOnly:function(){$(".breadcrumb").html($(".breadcrumb").html()+" (read-only)")},breadcrumb:function(){$("#subNavigationBar .breadcrumb").html("Collection: "+this.collectionName)},renderInfoView:function(){if(this.model.get("locked"))return 0;var n=function(e,t,i){if(e)arangoHelper.arangoError("Figures","Could not get revision.");else{frontendConfig.isCluster&&0===i.figures.alive.size&&0===i.figures.alive.count&&0===i.figures.datafiles.count&&0===i.figures.datafiles.fileSize&&0===i.figures.journals.count&&0===i.figures.journals.fileSize&&0===i.figures.compactors.count&&0===i.figures.compactors.fileSize&&0===i.figures.dead.size&&0===i.figures.dead.count&&(i.walMessage=" - not ready yet - ");var n={figures:i,revision:t,model:this.model};window.modalView.show("modalCollectionInfo.ejs","Collection: "+this.model.get("name"),[],n,null,null,null,null,null,"content")}}.bind(this),e=function(e,t){if(e)arangoHelper.arangoError("Figures","Could not get figures.");else{var i=t;this.model.getRevision(n,i)}}.bind(this);this.model.getFigures(e)}})}(),function(){"use strict";window.ServiceInstallGitHubView=Backbone.View.extend({el:"#content",readOnly:!1,template:templateEngine.createTemplate("serviceInstallGitHubView.ejs"),remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},initialize:function(){window.App.replaceApp&&(this._upgrade=!0)},events:{"click #installGitHubService":"installGitHubService","keydown input":"checkValidators"},checkValidators:function(){1!==window.modalView._validators.length&&(window.modalView.clearValidators(),this.setGithubValidators())},render:function(){return $(this.el).html(this.template.render({services:this.collection,upgrade:this._upgrade})),this.breadcrumb(),this.setGithubValidators(),arangoHelper.createTooltips(".modalTooltips"),this},breadcrumb:function(){var e=this;if(window.App.naviView){var t="New";this._upgrade&&(t="Replace ("+window.App.replaceAppData.mount+")"),$("#subNavigationBar .breadcrumb").html('Services: '+t),arangoHelper.buildServicesSubNav("GitHub")}else window.setTimeout(function(){e.breadcrumb()},100)},installGitHubService:function(){arangoHelper.createMountPointModal(this.installFoxxFromGithub.bind(this))},installFoxxFromGithub:function(){if(window.modalView.modalTestAll()){var e,t,i,n;this._upgrade?(t=window.App.replaceAppData.mount,i=arangoHelper.getFoxxFlag()):"/"!==(t=window.arangoHelper.escapeHtml($("#new-app-mount").val())).charAt(0)&&(t="/"+t),e=window.arangoHelper.escapeHtml($("#repository").val()),""===window.arangoHelper.escapeHtml($("#tag").val())&&"master";var o={url:window.arangoHelper.escapeHtml($("#repository").val()),version:window.arangoHelper.escapeHtml($("#tag").val())};try{Joi.assert(e,Joi.string().regex(/^[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+$/))}catch(e){return}n=Boolean($("#github-app-islegacy").prop("checked")),this.collection.installFromGithub(o,t,this.installCallback.bind(this),n,i)}},installCallback:function(e){window.App.navigate("#services",{trigger:!0}),window.App.applicationsView.installCallback(e)},setGithubValidators:function(){window.modalView.modalBindValidation({id:"repository",validateInput:function(){return[{rule:Joi.string().required().regex(/^[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+$/),msg:"No valid Github account and repository."}]}}),window.modalView.modalTestAll()}})}(),function(){"use strict";window.ServiceInstallNewView=Backbone.View.extend({el:"#content",readOnly:!1,template:templateEngine.createTemplate("serviceInstallNewView.ejs"),remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},events:{"click #installNewService":"installNewService","keydown input":"checkValidators"},checkValidators:function(){4!==window.modalView._validators.length&&(window.modalView.clearValidators(),this.setNewAppValidators())},initialize:function(){window.App.replaceApp&&(this._upgrade=!0)},render:function(){return $(this.el).html(this.template.render({services:this.collection,upgrade:this._upgrade})),this.renderSelects(),this.breadcrumb(),this.setNewAppValidators(),arangoHelper.createTooltips(".modalTooltips"),this},installNewService:function(){arangoHelper.createMountPointModal(this.generateNewFoxxApp.bind(this))},generateNewFoxxApp:function(){if(window.modalView.modalTestAll()){var e,t;this._upgrade?(e=window.App.replaceAppData.mount,t=arangoHelper.getFoxxFlag()):"/"!==(e=window.arangoHelper.escapeHtml($("#new-app-mount").val())).charAt(0)&&(e="/"+e);var i={name:window.arangoHelper.escapeHtml($("#new-app-name").val()),documentCollections:_.map($("#new-app-document-collections").select2("data"),function(e){return window.arangoHelper.escapeHtml(e.text)}),edgeCollections:_.map($("#new-app-edge-collections").select2("data"),function(e){return window.arangoHelper.escapeHtml(e.text)}),author:window.arangoHelper.escapeHtml($("#new-app-author").val()),license:window.arangoHelper.escapeHtml($("#new-app-license").val()),description:window.arangoHelper.escapeHtml($("#new-app-description").val())};this.collection.generate(i,e,this.installCallback.bind(this),t)}window.modalView.hide()},checkValidation:function(){window.modalView.modalTestAll()},installCallback:function(e){window.App.navigate("#services",{trigger:!0}),window.App.applicationsView.installCallback(e)},renderSelects:function(){$("#new-app-document-collections").select2({tags:[],showSearchBox:!1,minimumResultsForSearch:-1,width:"336px"}),$("#new-app-edge-collections").select2({tags:[],showSearchBox:!1,minimumResultsForSearch:-1,width:"336px"})},setNewAppValidators:function(){window.modalView.modalBindValidation({id:"new-app-author",validateInput:function(){return[{rule:Joi.string().required().min(1),msg:"Has to be non empty."}]}}),window.modalView.modalBindValidation({id:"new-app-name",validateInput:function(){return[{rule:Joi.string().required().regex(/^[a-zA-Z\-_][a-zA-Z0-9\-_]*$/),msg:"Can only contain a to z, A to Z, 0-9, '-' and '_'. Cannot start with a number."}]}}),window.modalView.modalBindValidation({id:"new-app-description",validateInput:function(){return[{rule:Joi.string().required().min(1),msg:"Has to be non empty."}]}}),window.modalView.modalBindValidation({id:"new-app-license",validateInput:function(){return[{rule:Joi.string().required().regex(/^[a-zA-Z0-9 .,;-]+$/),msg:"Can only contain a to z, A to Z, 0-9, '-', '.', ',' and ';'."}]}}),window.modalView.modalTestAll()},breadcrumb:function(){var e=this;if(window.App.naviView){var t="New";this._upgrade&&(t="Replace ("+window.App.replaceAppData.mount+")"),$("#subNavigationBar .breadcrumb").html('Services: '+t),arangoHelper.buildServicesSubNav("New")}else window.setTimeout(function(){e.breadcrumb()},100)}})}(),function(){"use strict";window.ServiceInstallView=Backbone.View.extend({el:"#content",readOnly:!1,foxxStoreRetry:0,template:templateEngine.createTemplate("serviceInstallView.ejs"),remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},events:{"click #categorySelection":"renderCategories","click #foxxFilters":"resetFilters","keyup #foxxSearch":"search"},initialize:function(e){this.functionsCollection=e.functionsCollection,window.App.replaceApp&&(this._upgrade=!0)},fetchStore:function(){var e=this;this.foxxStoreRetry=1,this.collection.fetch({cache:!1,success:function(){"#services/install"===window.location.hash&&e.render()}})},search:function(){this._installedSubViews[Object.keys(this._installedSubViews)[0]].applyFilter();var t=$("#foxxSearch").val();t?_.each(this._installedSubViews,function(e){e.model.get("name").includes(t)?"true"===$(e.el).attr("shown")&&$(e.el).show():$(e.el).hide()}):this._installedSubViews[Object.keys(this._installedSubViews)[0]].applyFilter()},createSubViews:function(){var i=this;this._installedSubViews={},i.collection.each(function(e){var t=new window.FoxxRepoView({collection:i.functionsCollection,model:e,appsView:i,upgrade:i._upgrade});i._installedSubViews[e.get("name")]=t})},renderCategories:function(e){this._installedSubViews[Object.keys(this._installedSubViews)[0]].renderCategories(e)},resetFilters:function(){$("#foxxSearch").val(""),this._installedSubViews[Object.keys(this._installedSubViews)[0]].resetFilters()},render:function(){if($(this.el).html(this.template.render({services:this.collection})),arangoHelper.buildServicesSubNav("Store"),this.breadcrumb(),0!==this.collection.length||0!==this.foxxStoreRetry)return this.collection.sort(),this.createSubViews(),_.each(this._installedSubViews,function(e){$("#availableFoxxes").append(e.render())}),this;this.fetchStore()},breadcrumb:function(){var e="New";this._upgrade&&(e="Replace ("+window.App.replaceAppData.mount+")"),$("#subNavigationBar .breadcrumb").html('Services: '+e)}})}(),function(){"use strict";window.ServiceInstallUploadView=Backbone.View.extend({el:"#content",readOnly:!1,template:templateEngine.createTemplate("serviceInstallUploadView.ejs"),remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},initialize:function(){window.App.replaceApp&&(this._upgrade=!0)},events:{"click #installUploadService":"installFromUpload"},render:function(){return $(this.el).html(this.template.render({services:this.collection,upgrade:this._upgrade})),this.prepareUpload(),this.breadcrumb(),arangoHelper.createTooltips(".modalTooltips"),this},installFromUpload:function(){arangoHelper.createMountPointModal(this.installFoxxFromZip.bind(this))},testFunction:function(e,t){window.foxxData||(window.foxxData={}),window.foxxData.files=e,window.foxxData.data=t,$("#installUploadService").attr("disabled",!1)},prepareUpload:function(){$("#upload-foxx-zip").uploadFile({url:arangoHelper.databaseUrl("/_api/upload?multipart=true"),allowedTypes:"zip,js",multiple:!1,onSuccess:this.testFunction})},installFoxxFromZip:function(){var e,t,i;void 0===window.foxxData.data?window.foxxData.data=this._uploadData:this._uploadData=window.foxxData.data,window.foxxData.data&&window.modalView.modalTestAll()&&(this._upgrade?(e=window.App.replaceAppData.mount,t=arangoHelper.getFoxxFlag()):"/"!==(e=window.arangoHelper.escapeHtml($("#new-app-mount").val())).charAt(0)&&(e="/"+e),i=Boolean($("#zip-app-islegacy").prop("checked")),this.collection.installFromZip(window.foxxData.data.filename,e,this.installCallback.bind(this),i,t));window.modalView.hide()},installCallback:function(e){window.App.navigate("#services",{trigger:!0}),window.App.applicationsView.installCallback(e)},breadcrumb:function(){var e=this;if(window.App.naviView){var t="New";this._upgrade&&(t="Replace ("+window.App.replaceAppData.mount+")"),$("#subNavigationBar .breadcrumb").html('Services: '+t),arangoHelper.buildServicesSubNav("Upload")}else window.setTimeout(function(){e.breadcrumb()},100)}})}(),function(){"use strict";window.ServiceInstallUrlView=Backbone.View.extend({el:"#content",readOnly:!1,template:templateEngine.createTemplate("serviceInstallUrlView.ejs"),remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},initialize:function(){window.App.replaceApp&&(this._upgrade=!0)},events:{"click #installUrlService":"installUrlService"},render:function(){return $(this.el).html(this.template.render({services:this.collection,upgrade:this._upgrade})),this.breadcrumb(),this.setUrlValidators(),arangoHelper.createTooltips(".modalTooltips"),this},breadcrumb:function(){var e=this;if(window.App.naviView){var t="New";this._upgrade&&(t="Replace ("+window.App.replaceAppData.mount+")"),$("#subNavigationBar .breadcrumb").html('Services: '+t),arangoHelper.buildServicesSubNav("Remote")}else window.setTimeout(function(){e.breadcrumb()},100)},installUrlService:function(){arangoHelper.createMountPointModal(this.installFoxxFromUrl.bind(this))},installFoxxFromUrl:function(){if(window.modalView.modalTestAll()){var e,t;this._upgrade?(e=window.App.replaceAppData.mount,t=arangoHelper.getFoxxFlag()):"/"!==(e=window.arangoHelper.escapeHtml($("#new-app-mount").val())).charAt(0)&&(e="/"+e);var i={url:window.arangoHelper.escapeHtml($("#repository").val()),version:"master"};this.collection.installFromUrl(i,e,this.installCallback.bind(this),null,t)}},setUrlValidators:function(){window.modalView.modalBindValidation({id:"repository",validateInput:function(){return[{rule:Joi.string().required().regex(/^(http)|^(https)/),msg:"No valid http or https url."}]}}),window.modalView.modalTestAll()},installCallback:function(e){window.App.navigate("#services",{trigger:!0}),window.App.applicationsView.installCallback(e)}})}(),function(){"use strict";window.LoggerView=Backbone.View.extend({el:"#content",logsel:"#logEntries",id:"#logContent",initDone:!1,pageSize:20,currentPage:0,logTopics:{},logLevels:[],remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},initialize:function(e){var t=this;e&&(this.options=e),this.collection.setPageSize(this.pageSize),this.initDone||$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/log/level"),contentType:"application/json",processData:!1,success:function(e){t.logTopics=e,_.each(["fatal","error","warning","info","debug"],function(e){t.logLevels.push(e)}),t.initDone=!0}})},currentLoglevel:void 0,defaultLoglevel:"info",events:{"click #logLevelSelection":"renderLogLevel","click #logTopicSelection":"renderLogTopic","click #logFilters":"resetFilters","click #loadMoreEntries":"loadMoreEntries"},template:templateEngine.createTemplate("loggerView.ejs"),templateEntries:templateEngine.createTemplate("loggerViewEntries.ejs"),renderLogTopic:function(e){var i,n=this;this.logTopicOptions||(this.logTopicOptions={}),_.each(this.logTopics,function(e,t){n.logTopicOptions[t]&&(i=n.logTopicOptions[t].active),n.logTopicOptions[t]={name:t,active:i||!1}});var t=$(e.currentTarget).position();t.right="30",this.logTopicView=new window.FilterSelectView({name:"Topic",options:n.logTopicOptions,position:t,callback:n.logTopicCallbackFunction.bind(this),multiple:!0}),this.logTopicView.render()},loadMoreEntries:function(){this.convertModelToJSON()},logTopicCallbackFunction:function(e){this.logTopicOptions=e,this.applyFilter()},logLevelCallbackFunction:function(e){this.logLevelOptions=e,this.applyFilter()},resetFilters:function(){_.each(this.logTopicOptions,function(e){e.active=!1}),_.each(this.logLevelOptions,function(e){e.active=!1}),this.applyFilter()},isFilterActive:function(e){var t=!1;return _.each(e,function(e){e.active&&(t=!0)}),t},changeButton:function(e){e?("level"===e?($("#logLevelSelection").addClass("button-success").removeClass("button-default"),$("#logTopicSelection").addClass("button-default").removeClass("button-success"),$("#filterDesc").html(e)):"topic"===e?($("#logTopicSelection").addClass("button-success").removeClass("button-default"),$("#logLevelSelection").addClass("button-default").removeClass("button-success"),$("#filterDesc").html(e)):"both"===e&&($("#logTopicSelection").addClass("button-success").removeClass("button-default"),$("#logLevelSelection").addClass("button-success").removeClass("button-default"),$("#filterDesc").html("level, topic")),$("#logFilters").show()):($("#logTopicSelection").addClass("button-default").removeClass("button-success"),$("#logLevelSelection").addClass("button-default").removeClass("button-success"),$("#logFilters").hide(),$("#filterDesc").html(""))},applyFilter:function(){var t=this,e=this.isFilterActive(this.logLevelOptions),i=this.isFilterActive(this.logTopicOptions);e&&i?(_.each($("#logEntries").children(),function(e){!1===t.logLevelOptions[$(e).attr("level")].active||!1===t.logTopicOptions[$(e).attr("topic")].active?$(e).hide():t.logLevelOptions[$(e).attr("level")].active&&t.logTopicOptions[$(e).attr("topic")].active&&$(e).show()}),this.changeButton("both")):e&&!i?(_.each($("#logEntries").children(),function(e){!1===t.logLevelOptions[$(e).attr("level")].active?$(e).hide():$(e).show()}),this.changeButton("level")):!e&&i?(_.each($("#logEntries").children(),function(e){!1===t.logTopicOptions[$(e).attr("topic")].active?$(e).hide():$(e).show()}),this.changeButton("topic")):e||i||(_.each($("#logEntries").children(),function(e){$(e).show()}),this.changeButton());var n=0;_.each($("#logEntries").children(),function(e){"flex"===$(e).css("display")&&$(e).css("display","block"),"block"===$(e).css("display")&&n++}),1===n?($(".logBorder").css("visibility","hidden"),$("#noLogEntries").hide()):0===n?$("#noLogEntries").show():($(".logBorder").css("visibility","visible"),$("#noLogEntries").hide())},renderLogLevel:function(e){var i,n=this;this.logLevelOptions||(this.logLevelOptions={}),_.each(this.logLevels,function(e){n.logLevelOptions[e]&&(i=n.logLevelOptions[e].active),n.logLevelOptions[e]={name:e,active:i||!1};var t=arangoHelper.statusColors[e];t&&(n.logLevelOptions[e].color=t)});var t=$(e.currentTarget).position();t.right="115",this.logLevelView=new window.FilterSelectView({name:"Level",options:n.logLevelOptions,position:t,callback:n.logLevelCallbackFunction.bind(this),multiple:!1}),this.logLevelView.render()},setActiveLoglevel:function(e){},initTotalAmount:function(){var e=this;this.collection.fetch({data:$.param({test:!0}),success:function(){e.convertModelToJSON()}}),this.fetchedAmount=!0},invertArray:function(e){var t,i=[],n=0;for(t=e.length-1;0<=t;t--)i[n]=e[t],n++;return i},convertModelToJSON:function(){if(this.fetchedAmount){this.collection.page=this.currentPage,this.currentPage++;var t,i=this,n=[];this.collection.fetch({success:function(e){i.collection.each(function(e){t=new Date(1e3*e.get("timestamp")),n.push({status:e.getLogStatus(),date:arangoHelper.formatDT(t),timestamp:e.get("timestamp"),msg:e.get("text"),topic:e.get("topic")})}),i.renderLogs(i.invertArray(n),e.lastInverseOffset)}})}else this.initTotalAmount()},render:function(){var e=this;return this.currentPage=0,this.initDone?($(this.el).html(this.template.render({})),this.convertModelToJSON()):window.setTimeout(function(){e.render()},100),this},renderLogs:function(e,t){_.each(e,function(e){-1"+t+""):$("#loginDatabase").append("")})}else $("#loginDatabase").hide(),$(".fa-database").hide(),$("#loginDatabase").after('');o.renderDBS()}).error(function(){t?t():location.reload(!0)})}if(frontendConfig.authenticationEnabled&&!0!==e){var i=arangoHelper.getCurrentJwtUsername();if(null!==i&&"undefined"!==i&&void 0!==i){t(arangoHelper.getCurrentJwtUsername(),function(){o.collection.logout(),window.setTimeout(function(){$("#loginUsername").focus()},300)})}else window.setTimeout(function(){$("#loginUsername").focus()},300)}else frontendConfig.authenticationEnabled&&e?t(arangoHelper.getCurrentJwtUsername(),null):t(null,null);return $(".bodyWrapper").show(),o.checkVersion(),this},sortDatabases:function(e){var t;return t=frontendConfig.authenticationEnabled?(t=_.pairs(e),t=_.sortBy(t,function(e){return e[0].toLowerCase()}),_.object(t)):_.sortBy(e,function(e){return e.toLowerCase()})},checkVersion:function(){var t=this;window.setTimeout(function(){var e=document.getElementById("loginSVG").contentDocument;void 0!==frontendConfig.isEnterprise?(frontendConfig.isEnterprise?e.getElementById("logo-enterprise"):e.getElementById("logo-community")).setAttribute("visibility","visible"):t.checkVersion()},150)},clear:function(){$("#loginForm input").removeClass("form-error"),$(".wrong-credentials").hide()},keyPress:function(e){e.ctrlKey&&13===e.keyCode?(e.preventDefault(),this.validate()):e.metaKey&&13===e.keyCode&&(e.preventDefault(),this.validate())},validate:function(e){e.preventDefault(),this.clear();var t=$("#loginUsername").val(),i=$("#loginPassword").val();t&&this.collection.login(t,i,this.loginCallback.bind(this,t,i))},loginCallback:function(e,t,i){var n=this;if(i){if(0===n.loginCounter)return n.loginCounter++,void n.collection.login(e,t,this.loginCallback.bind(this,e));n.loginCounter=0,$(".wrong-credentials").show(),$("#loginDatabase").html(""),$("#loginDatabase").append("")}else n.renderDBSelection(e)},renderDBSelection:function(e){var i=this,t=arangoHelper.databaseUrl("/_api/user/"+encodeURIComponent(e)+"/database","_system");!1===frontendConfig.authenticationEnabled&&(t=arangoHelper.databaseUrl("/_api/database/user")),$(".wrong-credentials").hide(),i.loggedIn=!0,$.ajax(t).success(function(e){if($("#loginForm").hide(),$(".login-window #databases").show(),$("#loginDatabase").html(""),0"+t+""):$("#loginDatabase").append("")})}else $("#loginDatabase").hide(),$(".fa-database").hide(),$("#loginDatabase").after('');i.renderDBS()}).error(function(){$(".wrong-credentials").show()})},renderDBS:function(){var e="Select DB: ";$("#noAccess").hide(),0===$("#loginDatabase").children().length?$("#loginDatabase").is(":visible")?($("#dbForm").remove(),$(".login-window #databases").prepend('
&'"]/)),i.push(window.modalView.createSuccessButton("Yes",e.bind(this,t))),window.modalView.show("modalTable.ejs","Modify Cluster Size",i,n)},initialize:function(){var e=this;clearInterval(this.intervalFunction),window.App.isCluster&&(this.updateServerTime(),this.intervalFunction=window.setInterval(function(){"#nodes"===window.location.hash&&e.render(!1)},this.interval))},deleteNode:function(e){if(!$(e.currentTarget).hasClass("noHover")){var t=this,i=$(e.currentTarget.parentNode.parentNode).attr("node").slice(0,-5);return window.confirm("Do you want to delete this node?")&&$.ajax({type:"POST",url:arangoHelper.databaseUrl("/_admin/cluster/removeServer"),contentType:"application/json",async:!0,data:JSON.stringify(i),success:function(e){t.render(!1)},error:function(){"#nodes"===window.location.hash&&arangoHelper.arangoError("Cluster","Could not fetch cluster information")}}),!1}},navigateToNode:function(e){var t=$(e.currentTarget).attr("node").slice(0,-5);$(e.currentTarget).hasClass("noHover")||window.App.navigate("#node/"+encodeURIComponent(t),{trigger:!0})},render:function(e){if("#nodes"===window.location.hash){var i=this;$("#content").is(":empty")&&arangoHelper.renderEmpty("Please wait. Requesting cluster information...","fa fa-spin fa-circle-o-notch"),!1!==e&&arangoHelper.buildNodesSubNav("Overview");$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/health"),contentType:"application/json",processData:!1,async:!0,success:function(e){"#nodes"===window.location.hash&&function(t){$.ajax({type:"GET",url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",success:function(e){"#nodes"===window.location.hash&&i.continueRender(t,e)}})}(e.Health)},error:function(){"#nodes"===window.location.hash&&arangoHelper.arangoError("Cluster","Could not fetch cluster information")}})}},continueRender:function(e,t){var i=[],n=[],o=!1;_.each(e,function(e,t){e.id=t,"Coordinator"===e.Role?i.push(e):"DBServer"===e.Role&&n.push(e)}),i=_.sortBy(i,function(e){return e.ShortName}),n=_.sortBy(n,function(e){return e.ShortName}),null!==t.numberOfDBServers&&null!==t.numberOfCoordinators&&(o=!0);var a=function(e){this.$el.html(this.template.render({coords:i,dbs:n,scaling:o,scaleProperties:e,plannedDBs:t.numberOfDBServers,plannedCoords:t.numberOfCoordinators})),o||($(".title").css("position","relative"),$(".title").css("top","-4px"),$(".sectionHeader .information").css("margin-top","-3px"))}.bind(this);this.renderCounts(o,a)},updatePlanned:function(e){e.numberOfCoordinators&&($("#plannedCoords").val(e.numberOfCoordinators),this.renderCounts(!0)),e.numberOfDBServers&&($("#plannedDBs").val(e.numberOfDBServers),this.renderCounts(!0))},setCoordSize:function(e){var t=this,i={numberOfCoordinators:e};$.ajax({type:"PUT",url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",data:JSON.stringify(i),success:function(){t.updatePlanned(i)},error:function(){arangoHelper.arangoError("Scale","Could not set coordinator size.")}})},setDBsSize:function(e){var t=this,i={numberOfDBServers:e};$.ajax({type:"PUT",url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",data:JSON.stringify(i),success:function(){t.updatePlanned(i)},error:function(){arangoHelper.arangoError("Scale","Could not set coordinator size.")}})},abortClusterPlanModal:function(){var e=[],t=[];t.push(window.modalView.createReadOnlyEntry("plan-abort-button","Caution","You are aborting the planned cluster plan. All pending servers are going to be removed. Continue?",void 0,void 0,!1,/[<>&'"]/)),e.push(window.modalView.createSuccessButton("Yes",this.abortClusterPlan.bind(this))),window.modalView.show("modalTable.ejs","Modify Cluster Size",e,t)},abortClusterPlan:function(){window.modalView.hide();try{var e=JSON.parse($("#infoCoords > .positive > span").text()),t=JSON.parse($("#infoDBs > .positive > span").text());this.setCoordSize(e),this.setDBsSize(t)}catch(e){arangoHelper.arangoError("Plan","Could not abort Cluster Plan")}},renderCounts:function(a,s){function l(e,t,i,n){var o=''+t+'';i&&!0===a&&(o=o+''+i+''),n&&(o=o+''+n+''),$(e).html(o),a||($(".title").css("position","relative"),$(".title").css("top","-4px"))}var c=this;$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/health"),contentType:"application/json",processData:!1,success:function(e){!function(e){var t=0,i=0,n=0,o=0,a=0,r=0;_.each(e,function(e){"Coordinator"===e.Role?"GOOD"===e.Status?i++:t++:"DBServer"===e.Role&&("GOOD"===e.Status?o++:a++)}),$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",processData:!1,success:function(e){n=Math.abs(i+t-e.numberOfCoordinators),r=Math.abs(o+a-e.numberOfDBServers),s?s({coordsPending:n,coordsOk:i,coordsErrors:t,dbsPending:r,dbsOk:o,dbsErrors:a}):(l("#infoDBs",o,r,a),l("#infoCoords",i,n,t)),c.isPlanFinished()||($(".scaleGroup").addClass("no-hover"),$("#plannedCoords").attr("disabled","disabled"),$("#plannedDBs").attr("disabled","disabled"))}})}(e.Health)}})},isPlanFinished:function(){return!(0<$("#infoDBs").find(".warning").length)&&!(0<$("#infoCoords").find(".warning").length)},addCoord:function(){this.isPlanFinished()?this.changePlanModal(function(){window.modalView.hide(),this.setCoordSize(this.readNumberFromID("#plannedCoords",!0))}.bind(this)):(arangoHelper.arangoNotification("Cluster Plan","Planned state not yet finished."),$(".noty_buttons .button-danger").remove())},removeCoord:function(){this.isPlanFinished()?this.changePlanModal(function(){window.modalView.hide(),this.setCoordSize(this.readNumberFromID("#plannedCoords",!1,!0))}.bind(this)):(arangoHelper.arangoNotification("Cluster Plan","Planned state not yet finished."),$(".noty_buttons .button-danger").remove())},addDBs:function(){this.isPlanFinished()?this.changePlanModal(function(){window.modalView.hide(),this.setDBsSize(this.readNumberFromID("#plannedDBs",!0))}.bind(this)):(arangoHelper.arangoNotification("Cluster Plan","Planned state not yet finished."),$(".noty_buttons .button-danger").remove())},removeDBs:function(){this.isPlanFinished()?this.changePlanModal(function(){window.modalView.hide(),this.setDBsSize(this.readNumberFromID("#plannedDBs",!1,!0))}.bind(this)):(arangoHelper.arangoNotification("Cluster Plan","Planned state not yet finished."),$(".noty_buttons .button-danger").remove())},readNumberFromID:function(e,t,i){var n=$(e).val(),o=!1;try{o=JSON.parse(n)}catch(e){}return t&&o++,i&&1!==o&&o--,o},updateServerTime:function(){this.serverTime=(new Date).getTime()}})}(),function(){"use strict";window.NodeView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("nodeView.ejs"),interval:5e3,dashboards:[],events:{},initialize:function(e){window.App.isCluster&&(this.coordinators=e.coordinators,this.dbServers=e.dbServers,this.coordid=e.coordid,this.updateServerTime())},remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},breadcrumb:function(e){$("#subNavigationBar .breadcrumb").html("Node: "+e)},render:function(){this.$el.html(this.template.render({coords:[]}));var e=function(){this.continueRender(),this.breadcrumb(arangoHelper.getCoordinatorShortName(this.coordid)),$(window).trigger("resize")}.bind(this);this.initCoordDone||this.waitForCoordinators(),this.initDBDone?(this.coordid=window.location.hash.split("/")[1],this.coordinator=this.coordinators.findWhere({id:this.coordid}),e()):this.waitForDBServers(e)},continueRender:function(){var e,t=this;if(this.coordinator)e=this.coordinator.get("name"),this.dashboards[e]&&this.dashboards[e].clearInterval(),this.dashboards[e]=new window.DashboardView({dygraphConfig:window.dygraphConfig,database:window.App.arangoDatabase,serverToShow:{raw:this.coordinator.get("address"),isDBServer:!1,endpoint:this.coordinator.get("protocol")+"://"+this.coordinator.get("address"),target:this.coordinator.get("id")}});else{var i=this.dbServer.toJSON();e=i.name,this.dashboards[e]&&this.dashboards[e].clearInterval(),this.dashboards[e]=new window.DashboardView({dygraphConfig:null,database:window.App.arangoDatabase,serverToShow:{raw:i.address,isDBServer:!0,endpoint:i.endpoint,id:i.id,name:i.name,status:i.status,target:i.id}})}this.dashboards[e].render(),window.setTimeout(function(){t.dashboards[e].resize()},500)},waitForCoordinators:function(e){var t=this;window.setTimeout(function(){0===t.coordinators.length?t.waitForCoordinators(e):(t.coordinator=t.coordinators.findWhere({id:t.coordid}),t.initCoordDone=!0,e&&e())},200)},waitForDBServers:function(e){var i=this;window.setTimeout(function(){0===i.dbServers[0].length?i.waitForDBServers(e):(i.initDBDone=!0,i.dbServer=i.dbServers[0],i.dbServer.each(function(e){var t=e.get("id");t===window.location.hash.split("/")[1]&&(i.dbServer=i.dbServer.findWhere({id:t}))}),e())},200)},updateServerTime:function(){this.serverTime=(new Date).getTime()}})}(),function(){"use strict";window.NotificationView=Backbone.View.extend({events:{"click .navlogo #stat_hd":"toggleNotification","click .notificationItem .fa":"removeNotification","click #removeAllNotifications":"removeAllNotifications"},initialize:function(){this.collection.bind("add",this.renderNotifications.bind(this)),this.collection.bind("remove",this.renderNotifications.bind(this)),this.collection.bind("reset",this.renderNotifications.bind(this)),window.setTimeout(function(){!1===frontendConfig.authenticationEnabled&&!1===frontendConfig.isCluster&&!0===arangoHelper.showAuthDialog()&&window.arangoHelper.arangoWarning("Warning","Authentication is disabled. Do not use this setup in production mode.")},2e3)},notificationItem:templateEngine.createTemplate("notificationItem.ejs"),el:"#notificationBar",template:templateEngine.createTemplate("notificationView.ejs"),toggleNotification:function(){0!==this.collection.length&&$("#notification_menu").toggle()},removeAllNotifications:function(){$.noty.clearQueue(),$.noty.closeAll(),this.collection.reset(),$("#notification_menu").hide()},removeNotification:function(e){var t=e.target.id;this.collection.get(t).destroy()},renderNotifications:function(e,t,i){if(i&&i.add){var n,o=this.collection.at(this.collection.length-1),a=o.get("title"),r=5e3,s=["click"];if(o.get("content")&&(a=a+": "+o.get("content")),"error"===o.get("type")?(r=!1,s=["button"],n=[{addClass:"button-danger",text:"Close",onClick:function(e){e.close()}}]):"warning"===o.get("type")&&(r=15e3,n=[{addClass:"button-warning",text:"Close",onClick:function(e){e.close()}},{addClass:"button-danger",text:"Don't show again.",onClick:function(e){e.close(),window.arangoHelper.doNotShowAgain()}}]),$.noty.clearQueue(),$.noty.closeAll(),noty({theme:"relax",text:a,template:'
This will generate a package containing a lot of commonly required information about your query and environment that helps the ArangoDB Team to reproduce your issue. This debug package will include:
collection names
collection indexes
attribute names
bind parameters
Additionally, samples of your data will be included with all string values obfuscated in a non-reversible way if below checkbox is ticked.
If disabled, this package will not include any data.
Please open the package locally and check if it contains anything that you are not allowed/willing to share and obfuscate it before uploading. Including this package in bug reports will lower the amount of questioning back and forth to reproduce the issue on our side and is much appreciated.
",void 0,!1,!1)),t.push(window.modalView.createCheckboxEntry("debug-download-package-examples","Include obfuscated examples","includeExamples","Includes an example set of documents, obfuscating all string values inside the data. This helps the ArangoDB Team as many issues are related to the document structure / format and the indexes defined on them.",!0)),e.push(window.modalView.createSuccessButton("Download Package",this.downloadDebugZip.bind(this))),window.modalView.show("modalTable.ejs","Download Query Debug Package",e,t,void 0,void 0)},downloadDebugZip:function(){if(!this.verifyQueryAndParams()){var e=this.aqlEditor.getValue();if(""!==e&&null!=e){var t={query:e,bindVars:this.bindParamTableObj||{},examples:$("#debug-download-package-examples").is(":checked")};arangoHelper.downloadPost("query/debugDump",JSON.stringify(t),function(){window.modalView.hide()},function(e,t){window.arangoHelper.arangoError("Debug Dump",e+": "+t),window.modalView.hide()})}else arangoHelper.arangoError("Query error","Could not create a debug package.")}},fillExplain:function(t,i,n){var e,o=this;if("false"!==(e=n?this.readQueryData(null,null,!0):this.readQueryData())&&($("#outputEditorWrapper"+i+" .queryExecutionTime").text(""),this.execPending=!1,e)){var a,r=function(){$("#outputEditorWrapper"+i+" #spinner").remove(),$("#outputEditor"+i).css("opacity","1"),$("#outputEditorWrapper"+i+" .fa-close").show(),$("#outputEditorWrapper"+i+" .switchAce").show()};a=n?arangoHelper.databaseUrl("/_admin/aardvark/query/profile"):arangoHelper.databaseUrl("/_admin/aardvark/query/explain"),$.ajax({type:"POST",url:a,data:e,contentType:"application/json",processData:!1,success:function(e){e.msg&&e.msg.errorMessage?(o.removeOutputEditor(i),n?arangoHelper.arangoError("Profile",e.msg):arangoHelper.arangoError("Explain",e.msg)):(o.cachedQueries[i]=e,t.setValue(e.msg,1),o.deselect(t),$.noty.clearQueue(),$.noty.closeAll(),o.handleResult(i),$(".centralRow").animate({scrollTop:$("#queryContent").height()},"fast")),r()},error:function(e){try{var t=JSON.parse(e.responseText);n?arangoHelper.arangoError("Profile",t.errorMessage):arangoHelper.arangoError("Explain",t.errorMessage)}catch(e){n?arangoHelper.arangoError("Profile","ERROR"):arangoHelper.arangoError("Explain","ERROR")}o.handleResult(i),o.removeOutputEditor(i),r()}})}},removeOutputEditor:function(e){$("#outputEditorWrapper"+e).hide(),$("#outputEditorWrapper"+e).remove(),0===$(".outputEditorWrapper").length&&$("#removeResults").hide()},getCachedQueryAfterRender:function(){if(!1===this.renderComplete&&this.aqlEditor){var e=this.getCachedQuery(),t=this;if(null!=e&&""!==e&&0"+_.escape(e)+" results")})},render:function(){this.refreshAQL(),this.renderComplete=!1,this.$el.html(this.template.render({})),this.afterRender(),this.initDone||(this.settings.aqlWidth=$(".aqlEditorWrapper").width()),"json"===this.bindParamMode&&this.toggleBindParams(),this.initDone=!0,this.renderBindParamTable(!0),this.restoreCachedQueries(),this.delegateEvents(),this.restoreQuerySize(),this.getCachedQueryAfterRender()},cleanupGraphs:function(){void 0===this.graphViewers&&null===this.graphViewers||(_.each(this.graphViewers,function(e){void 0!==e&&(e.killCurrentGraph(),e.remove())}),$("canvas").remove(),this.graphViewers=null,this.graphViewers=[])},afterRender:function(){var e=this;this.initAce(),this.initTables(),this.fillSelectBoxes(),this.makeResizeable(),this.initQueryImport(),$(".inputEditorWrapper").height($(window).height()/10*5+25),window.setTimeout(function(){e.resize()},10),e.deselect(e.aqlEditor)},restoreCachedQueries:function(){var i=this;0
",$("#replication-info").append(o)}},goToApplier:function(e){var t=btoa($(e.currentTarget).attr("data"));window.App.navigate("#replication/applier/"+t+"/"+btoa("_system"),{trigger:!0})},goToApplierFromTable:function(e){var t=btoa(window.location.origin),i=btoa($(e.currentTarget).find("#applier-database-id").html()),n=$(e.currentTarget).find("#applier-running-id").html();"true"===n||!0===n?window.App.navigate("#replication/applier/"+t+"/"+i,{trigger:!0}):arangoHelper.arangoMessage("Replication","This applier is not running.")},getActiveFailoverEndpoints:function(){var t=this;$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/cluster/endpoints"),contentType:"application/json",success:function(e){e.endpoints?t.renderEndpoints(e.endpoints):t.renderEndpoints()},error:function(){t.renderEndpoints()}})},renderEndpoints:function(e){var t=this;if(e){var i=e[0],n=e.slice(1,e.length);$("#nodes-leader-id").html(i.endpoint),$("#nodes-followers-id").html(""),_.each(n,function(e){$("#nodes-followers-id").append(''+e.endpoint+"")})}else $("#nodes-leader-id").html("Error"),$("#nodes-followers-id").html("Error")},parseEndpoint:function(e,t){var i;return"[::1]"===e.slice(6,11)?i=window.location.host.split(":")[0]+":"+e.split(":")[4]:"tcp://"===e.slice(0,6)?i="http://"+e.slice(6,e.length):"ssl://"===e.slice(0,6)&&(i="https://"+e.slice(6,e.length)),t&&(i=window.location.protocol+"//"+i),i||e},getLoggerState:function(){var t=this;$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/replication/logger-state"),contentType:"application/json",success:function(e){"#replication"===window.location.hash?(t.updateLoggerGraphsData(e),t.nvchartsInit?t.rerenderLoggerGraphs():t.initLoggerGraphs(),t.renderLoggerState(e.server,e.clients,e.state)):t.updateLoggerGraphsData(e)},error:function(){arangoHelper.arangoError("Replication","Could not fetch the leaders logger state.")}})},getApplierStates:function(t){var e,i=this;e=t?arangoHelper.databaseUrl("/_api/replication/applier-state?global=true"):arangoHelper.databaseUrl("/_api/replication/applier-state-all"),$.ajax({type:"GET",cache:!1,url:e,contentType:"application/json",success:function(e){t?i.renderApplierState(e,!0):i.renderApplierState(e)},error:function(){t?arangoHelper.arangoError("Replication","Could not fetch the followers global applier state."):arangoHelper.arangoError("Replication","Could not fetch the followers applier state.")}})},renderApplierState:function(i,e){var o,a=this;e&&(i.database="All databases",i={"All databases":i});var r,s=0,n=[],l=[];_.each(i,function(e,t){e.state.running?n.push(i[t]):(i[t].database=t,l.push(i[t]))}),n=_.sortBy(n,"database"),l=_.sortBy(l,"database"),i=n.concat(l),$("#repl-follower-table tbody").html(""),_.each(i,function(e,t){var i;o="undefined"!==e.endpoint&&e.endpoint?a.parseEndpoint(e.endpoint):"not available","inactive"!==e.state.phase&&!0!==e.state.running&&s++;var n="active";"inactive"===e.state.phase&&(n="inactive"),0===e.state.lastError.errorNum?i="inactive"!==e.state.phase||e.state.running?'':"n/a":(i='',s++),$("#repl-follower-table tbody").append('
'+e.database+'
'+e.state.running+"
"+e.state.phase+'
'+o+"
"+e.state.lastAppliedContinuousTick+"
"+i+"
"),r=e.server.serverId}),$("#logger-lastLogTick-id").html(r),0===s?this.renderHealth(!1):this.renderHealth(!0,"Some appliers are not running or do have errors.")},renderHealth:function(e,t){e?($("#info-msg-id").addClass("negative"),$("#info-msg-id").removeClass("positive"),$("#info-msg-id").html('Bad '),t&&($("#info-msg-id").attr("title",t),$("#info-msg-id").addClass("modalTooltips"),arangoHelper.createTooltips(".modalTooltips"))):($("#info-msg-id").addClass("positive"),$("#info-msg-id").removeClass("negative"),$("#info-msg-id").removeClass("modalTooltips"),$("#info-msg-id").html('Good '))},getStateData:function(e){3===this.mode?(this.getActiveFailoverEndpoints(),this.getLoggerState()):2===this.mode?"leader"===this.info.role?this.getLoggerState():this.getApplierStates(!0):1===this.mode&&("leader"===this.info.role?this.getLoggerState():this.getApplierStates()),e&&e()},updateLoggerGraphsData:function(e){this.loggerGraphsData.length>this.keepEntries&&this.loggerGraphsData.pop(),this.loggerGraphsData.push(e)},parseLoggerData:function(){var e,o=this,t=this.loggerGraphsData;this.colors||(this.colors=randomColor({hue:"blue",count:this.loggerGraphsData.length}));var a={leader:{key:e=3===o.mode?"Leader":"Master",values:[],strokeWidth:2,color:"#2ecc71"}},r={leader:{key:e,values:[],strokeWidth:2,color:"#2ecc71"}};return _.each(t,function(i){a.leader.values.push({x:Date.parse(i.state.time),y:0}),r.leader.values.push({x:Date.parse(i.state.time),y:0});var n=0;_.each(i.clients,function(e){var t;a[e.serverId]||(t=3===o.mode?"Follower ("+e.serverId+")":"Slave ("+e.serverId+")",a[e.serverId]={key:t,color:o.colors[n],strokeWidth:1,values:[]},r[e.serverId]={key:t,color:o.colors[n],strokeWidth:1,values:[]},n++);a[e.serverId].values.push({x:Date.parse(e.time),y:(Date.parse(i.state.time)-Date.parse(e.time))/1e3*-1}),r[e.serverId].values.push({x:Date.parse(e.time),y:-1*(i.state.lastLogTick-e.lastServedTick)})})}),{graphDataTick:_.toArray(r),graphDataTime:_.toArray(a)}},initLoggerGraphs:function(){var t=this;nv.addGraph(function(){t.charts.replicationTimeChart=nv.models.lineChart().options({duration:300,useInteractiveGuideline:!0,forceY:[2,-10]}),t.charts.replicationTimeChart.xAxis.axisLabel("").tickFormat(function(e){var t=new Date(e);return(t.getHours()<10?"0":"")+t.getHours()+":"+(t.getMinutes()<10?"0":"")+t.getMinutes()+":"+(t.getSeconds()<10?"0":"")+t.getSeconds()}).staggerLabels(!1),t.charts.replicationTimeChart.yAxis.axisLabel("Last call ago (in s)").tickFormat(function(e){return null===e?"N/A":d3.format(",.0f")(e)});var e=t.parseLoggerData().graphDataTime;return d3.select("#replicationTimeChart svg").datum(e).call(t.charts.replicationTimeChart),nv.utils.windowResize(t.charts.replicationTimeChart.update),t.charts.replicationTimeChart}),nv.addGraph(function(){t.charts.replicationTickChart=nv.models.lineChart().options({duration:300,useInteractiveGuideline:!0,forceY:[2,void 0]}),t.charts.replicationTickChart.xAxis.axisLabel("").tickFormat(function(e){var t=new Date(e);return(t.getHours()<10?"0":"")+t.getHours()+":"+(t.getMinutes()<10?"0":"")+t.getMinutes()+":"+(t.getSeconds()<10?"0":"")+t.getSeconds()}).staggerLabels(!1),t.charts.replicationTickChart.yAxis.axisLabel("Ticks behind").tickFormat(function(e){return null===e?"N/A":d3.format(",.0f")(e)});var e=t.parseLoggerData().graphDataTick;return d3.select("#replicationTickChart svg").datum(e).call(t.charts.replicationTickChart),nv.utils.windowResize(t.charts.replicationTickChart.update),t.charts.replicationTickChart}),t.nvchartsInit=!0},rerenderLoggerGraphs:function(){d3.select("#replicationTimeChart svg").datum(this.parseLoggerData().graphDataTime).transition().duration(500).call(this.charts.replicationTimeChart),d3.select("#replicationTickChart svg").datum(this.parseLoggerData().graphDataTick).transition().duration(500).call(this.charts.replicationTickChart),_.each(this.charts,function(e){nv.utils.windowResize(e.update)})},renderLoggerState:function(e,t,i){e&&t&&i?($("#logger-running-id").html(i.running),$("#logger-version-id").html(e.version),$("#logger-serverid-id").html(e.serverId),$("#logger-time-id").html(i.time),$("#logger-lastLogTick-id").html(i.lastLogTick),$("#logger-totalEvents-id").html(i.totalEvents),$("#repl-logger-clients tbody").html(""),_.each(t,function(e){$("#repl-logger-clients tbody").append("
"+e.syncerId+"
"+e.serverId+"
"+e.clientInfo+"
"+e.time+"
"+e.lastServedTick+"
")}),i.running?this.renderHealth(!1):this.renderHealth(!0,"The logger thread is not running")):($("#logger-running-id").html("Error"),$("#logger-endpoint-id").html("Error"),$("#logger-version-id").html("Error"),$("#logger-serverid-id").html("Error"),$("#logger-time-id").html("Error"),this.renderHealth(!0,"Unexpected data from the logger thread."))},getMode:function(t){var i=this;$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/aardvark/replication/mode"),contentType:"application/json",success:function(e){!e.mode&&0!==e.mode||(Number.isInteger(e.mode)?(i.mode=e.mode,0!==e.mode?i.info.state="enabled":i.info.state="disabled"):i.mode="undefined",e.role&&(i.info.role=e.role),3===i.mode?(i.info.mode="Active Failover",i.info.level="Server"):2===i.mode?(i.info.mode="Master/Slave",i.info.level="Server"):1===i.mode&&(i.info.mode="Master/Slave","follower"===i.info.role?i.info.level="Database":i.info.level="Check slaves for details")),t&&t()},error:function(){arangoHelper.arangoError("Replication","Could not fetch the replication state.")}})}})}(),function(){"use strict";window.ScaleView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("scaleView.ejs"),interval:1e4,knownServers:[],events:{"click #addCoord":"addCoord","click #removeCoord":"removeCoord","click #addDBs":"addDBs","click #removeDBs":"removeDBs"},setCoordSize:function(e){var t=this,i={numberOfCoordinators:e};$.ajax({type:"PUT",url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",data:JSON.stringify(i),success:function(){t.updateTable(i)},error:function(){arangoHelper.arangoError("Scale","Could not set coordinator size.")}})},setDBsSize:function(e){var t=this,i={numberOfDBServers:e};$.ajax({type:"PUT",url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",data:JSON.stringify(i),success:function(){t.updateTable(i)},error:function(){arangoHelper.arangoError("Scale","Could not set coordinator size.")}})},addCoord:function(){this.setCoordSize(this.readNumberFromID("#plannedCoords",!0))},removeCoord:function(){this.setCoordSize(this.readNumberFromID("#plannedCoords",!1,!0))},addDBs:function(){this.setDBsSize(this.readNumberFromID("#plannedDBs",!0))},removeDBs:function(){this.setDBsSize(this.readNumberFromID("#plannedDBs",!1,!0))},readNumberFromID:function(e,t,i){var n=$(e).html(),o=!1;try{o=JSON.parse(n)}catch(e){}return t&&o++,i&&1!==o&&o--,o},initialize:function(e){var t=this;clearInterval(this.intervalFunction),window.App.isCluster&&"_system"===frontendConfig.db&&(this.dbServers=e.dbServers,this.coordinators=e.coordinators,this.updateServerTime(),this.intervalFunction=window.setInterval(function(){"#sNodes"===window.location.hash&&t.coordinators.fetch({success:function(){t.dbServers.fetch({success:function(){t.continueRender(!0)}})}})},this.interval))},render:function(){var e=this,t=function(){this.waitForDBServers(function(){e.continueRender()})}.bind(this);this.initDoneCoords?t():this.waitForCoordinators(t),window.arangoHelper.buildNodesSubNav("scale")},continueRender:function(e){var t,i,n=this;t=this.coordinators.toJSON(),i=this.dbServers.toJSON(),this.$el.html(this.template.render({runningCoords:t.length,runningDBs:i.length,plannedCoords:void 0,plannedDBs:void 0,initialized:e})),$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",processData:!1,success:function(e){n.updateTable(e)}})},updateTable:function(e){var t='scaling in progress ',i='no scaling process active';e.numberOfCoordinators&&($("#plannedCoords").html(e.numberOfCoordinators),this.coordinators.toJSON().length===e.numberOfCoordinators?$("#statusCoords").html(i):$("#statusCoords").html(t)),e.numberOfDBServers&&($("#plannedDBs").html(e.numberOfDBServers),this.dbServers.toJSON().length===e.numberOfDBServers?$("#statusDBs").html(i):$("#statusDBs").html(t))},waitForDBServers:function(e){var t=this;0===this.dbServers.length?window.setInterval(function(){t.waitForDBServers(e)},300):e()},waitForCoordinators:function(e){var t=this;window.setTimeout(function(){0===t.coordinators.length?t.waitForCoordinators(e):(t.initDoneCoords=!0,e())},200)},updateServerTime:function(){this.serverTime=(new Date).getTime()}})}(),function(){"use strict";window.SettingsView=Backbone.View.extend({el:"#content",readOnly:!1,initialize:function(e){this.collectionName=e.collectionName,this.model=this.collection},events:{},render:function(){this.breadcrumb(),arangoHelper.buildCollectionSubNav(this.collectionName,"Settings"),this.renderSettings()},breadcrumb:function(){$("#subNavigationBar .breadcrumb").html("Collection: "+this.collectionName)},unloadCollection:function(){if(!this.readOnly){var e=function(e){e?arangoHelper.arangoError("Collection error",this.model.get("name")+" could not be unloaded."):void 0===e?(this.model.set("status","unloading"),this.render()):"#collections"===window.location.hash?(this.model.set("status","unloaded"),this.render()):arangoHelper.arangoNotification("Collection "+this.model.get("name")+" unloaded.")}.bind(this);this.model.unloadCollection(e),window.modalView.hide()}},loadCollection:function(){if(!this.readOnly){var e=function(e){e?arangoHelper.arangoError("Collection error",this.model.get("name")+" could not be loaded."):void 0===e?(this.model.set("status","loading"),this.render()):"#collections"===window.location.hash?(this.model.set("status","loaded"),this.render()):arangoHelper.arangoNotification("Collection "+this.model.get("name")+" loaded.")}.bind(this);this.model.loadCollection(e),window.modalView.hide()}},truncateCollection:function(){this.readOnly||(this.model.truncateCollection(),$(".modal-delete-confirmation").hide(),window.modalView.hide())},warmupCollection:function(){this.readOnly||(this.model.warmupCollection(),$(".modal-delete-confirmation").hide(),window.modalView.hide())},deleteCollection:function(){this.readOnly||this.model.destroy({error:function(e,t){arangoHelper.arangoError("Could not drop collection: "+t.responseJSON.errorMessage)},success:function(){window.App.navigate("#collections",{trigger:!0})}})},saveModifiedCollection:function(){if(!this.readOnly){var e=function(e,t){if(e)arangoHelper.arangoError("Error","Could not get coordinator info");else{var i;i=t?this.model.get("name"):$("#change-collection-name").val();var n=this.model.get("status");if("loaded"===n){var a,r;if("rocksdb"!==frontendConfig.engine)try{a=JSON.parse(1024*$("#change-collection-size").val()*1024)}catch(e){return arangoHelper.arangoError("Please enter a valid journal size number."),0}if("rocksdb"!==frontendConfig.engine)try{if((r=JSON.parse($("#change-index-buckets").val()))<1||parseInt(r,10)!==Math.pow(2,Math.log2(r)))throw new Error("invalid indexBuckets value")}catch(e){return arangoHelper.arangoError("Please enter a valid number of index buckets."),0}var o=this,s=function(e,t){e?(o.render(),arangoHelper.arangoError("Collection error: "+t.responseJSON.errorMessage)):(arangoHelper.arangoNotification("Collection: Successfully changed."),window.App.navigate("#cSettings/"+i,{trigger:!0}))},l=function(e){var t=!1;if(e)arangoHelper.arangoError("Collection error: "+e.responseText);else{var i,n,o=$("#change-collection-sync").val();if(frontendConfig.isCluster){i=$("#change-replication-factor").val(),n=$("#change-min-replication-factor").val();try{Number.parseInt(n)>Number.parseInt(i)&&(arangoHelper.arangoError("Change Collection","Minimal replication factor is not allowed to be greater then replication factor"),t=!0)}catch(e){}}t||this.model.changeCollection(o,a,r,i,n,s)}}.bind(this);!1===frontendConfig.isCluster?this.model.renameCollection(i,l):l()}else if("unloaded"===n)if(this.model.get("name")!==i){var c=function(e,t){e?arangoHelper.arangoError("Collection"+t.responseText):(arangoHelper.arangoNotification("CollectionSuccessfully changed."),window.App.navigate("#cSettings/"+i,{trigger:!0}))};!1===frontendConfig.isCluster?this.model.renameCollection(i,c):c()}else window.modalView.hide()}}.bind(this);window.isCoordinator(e)}},changeViewToReadOnly:function(){window.App.settingsView.readOnly=!0,$(".breadcrumb").html($(".breadcrumb").html()+" (read-only)"),$(".modal-body input").prop("disabled","true"),$(".modal-body select").prop("disabled","true"),$(".modal-footer button").addClass("disabled"),$(".modal-footer button").unbind("click")},renderSettings:function(){var s=this,e=function(e,t){if(e)arangoHelper.arangoError("Error","Could not get coordinator info");else{var i=!1;"loaded"===this.model.get("status")&&(i=!0);var n=[],a=[];t||("_"===this.model.get("name").substr(0,1)?a.push(window.modalView.createReadOnlyEntry("change-collection-name","Name",this.model.get("name"),!1,"",!0,[{rule:Joi.string().regex(/^[a-zA-Z]/),msg:"Collection name must always start with a letter."},{rule:Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),msg:'Only Symbols "_" and "-" are allowed.'},{rule:Joi.string().required(),msg:"No collection name given."}])):a.push(window.modalView.createTextEntry("change-collection-name","Name",this.model.get("name"),!1,"",!0,[{rule:Joi.string().regex(/^[a-zA-Z]/),msg:"Collection name must always start with a letter."},{rule:Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),msg:'Only Symbols "_" and "-" are allowed.'},{rule:Joi.string().required(),msg:"No collection name given."}])));var r=function(){a.push(window.modalView.createReadOnlyEntry("change-collection-id","ID",this.model.get("id"),"")),a.push(window.modalView.createReadOnlyEntry("change-collection-type","Type",this.model.get("type"),"")),a.push(window.modalView.createReadOnlyEntry("change-collection-status","Status",this.model.get("status"),"")),n.push(window.modalView.createDeleteButton("Delete",this.deleteCollection.bind(this))),n.push(window.modalView.createDeleteButton("Truncate",this.truncateCollection.bind(this))),"rocksdb"===frontendConfig.engine&&n.push(window.modalView.createNotificationButton("Load Indexes into Memory",this.warmupCollection.bind(this))),i?n.push(window.modalView.createNotificationButton("Unload",this.unloadCollection.bind(this))):n.push(window.modalView.createNotificationButton("Load",this.loadCollection.bind(this))),n.push(window.modalView.createSuccessButton("Save",this.saveModifiedCollection.bind(this)));window.modalView.show(["modalTable.ejs","indicesView.ejs"],"Modify Collection",n,a,null,null,this.events,null,["General","Indexes"],"content"),$($("#infoTab").children()[1]).remove()}.bind(this);if(i){this.model.getProperties(function(e,t){if(e)arangoHelper.arangoError("Collection","Could not fetch properties");else{var i=t.waitForSync;if(t.journalSize){var n=t.journalSize/1048576,o=t.indexBuckets;a.push(window.modalView.createTextEntry("change-collection-size","Journal size",n,"The maximal size of a journal or datafile (in MB). Must be at least 1.","",!0,[{rule:Joi.string().allow("").optional().regex(/^[0-9]*$/),msg:"Must be a number."}]))}o&&a.push(window.modalView.createTextEntry("change-index-buckets","Index buckets",o,"The number of index buckets for this collection. Must be at least 1 and a power of 2.","",!0,[{rule:Joi.string().allow("").optional().regex(/^[1-9][0-9]*$/),msg:"Must be a number greater than 1 and a power of 2."}])),t.replicationFactor&&frontendConfig.isCluster&&("satellite"===t.replicationFactor?(a.push(window.modalView.createReadOnlyEntry("change-replication-factor","Replication factor",t.replicationFactor,"This collection is a satellite collection. The replicationFactor is not changeable.","",!0)),a.push(window.modalView.createReadOnlyEntry("change-min-replication-factor","Minimal replication factor",t.minReplicationFactor,"This collection is a satellite collection. The minReplicationFactor is not changeable.","",!0))):(a.push(window.modalView.createTextEntry("change-replication-factor","Replication factor",t.replicationFactor,"The replicationFactor parameter is the total number of copies being kept, that is, it is one plus the number of followers. Must be a number.","",!0,[{rule:Joi.string().allow("").optional().regex(/^[0-9]*$/),msg:"Must be a number."}])),a.push(window.modalView.createTextEntry("change-min-replication-factor","Minimal Replication factor",t.minReplicationFactor,"Numeric value. Must be at least 1. Must be smaller or equal compared to the replicationFactor. Total number of copies of the data in the cluster. If we get below this value the collection will be read-only until enough copies are created.","",!0,[{rule:Joi.string().allow("").optional().regex(/^[1-9]*$/),msg:"Must be a number. Must be at least 1 and has to be smaller or equal compared to the replicationFactor."}])))),a.push(window.modalView.createSelectEntry("change-collection-sync","Wait for sync",i,"Synchronize to disk before returning from a create or update of a document.",[{value:!1,label:"No"},{value:!0,label:"Yes"}]))}r(),arangoHelper.checkCollectionPermissions(s.collectionName,s.changeViewToReadOnly.bind(this))})}else r(),arangoHelper.checkCollectionPermissions(s.collectionName,s.changeViewToReadOnly.bind(this))}}.bind(this);window.isCoordinator(e)}})}(),function(){"use strict";window.ShardsView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("shardsView.ejs"),interval:1e4,knownServers:[],pending:!1,visibleCollection:null,events:{"click #shardsContent .shardLeader span":"moveShard","click #shardsContent .shardFollowers span":"moveShardFollowers","click #rebalanceShards":"rebalanceShards","click .sectionHeader":"toggleSections"},initialize:function(e){var t=this;t.dbServers=e.dbServers,clearInterval(this.intervalFunction),window.App.isCluster&&(this.updateServerTime(),this.intervalFunction=window.setInterval(function(){"#shards"===window.location.hash&&t.render(!1)},this.interval))},remove:function(){return clearInterval(this.intervalFunction),this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},renderArrows:function(e){$("#shardsContent .fa-arrow-down").removeClass("fa-arrow-down").addClass("fa-arrow-right"),$(e.currentTarget).find(".fa-arrow-right").removeClass("fa-arrow-right").addClass("fa-arrow-down")},toggleSections:function(e){var t=$(e.currentTarget).parent().attr("id");this.visibleCollection=t,$(".sectionShardContent").hide(),$(e.currentTarget).next().show(),this.renderArrows(e),this.getShardDetails(t)},renderShardDetail:function(i,e){var n=0,o=0,a=0;_.each(e.results[i].Plan,function(e,t){if(e.progress)if(0===e.progress.current){$("#"+i+"-"+t+" .shardProgress").html("n/A")}else n=(e.progress.current/e.progress.total*100).toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]+"%",$("#"+i+"-"+t+" .shardProgress").html(n);else $("#"+i+"-"+t+" .shardProgress").html(''),o++;a++}),a===o?($("#"+i+" .shardSyncIcons i").addClass("fa-check-circle").removeClass(".fa-times-circle"),$("#"+i+" .notInSync").addClass("inSync").removeClass("notInSync")):$("#"+i+" .shardSyncIcons i").addClass("fa-times-circle").removeClass("fa-check-circle")},checkActiveShardDisplay:function(){var t=this;_.each($(".sectionShard"),function(e){$(e).find(".sectionShardContent").is(":visible")&&t.getShardDetails($(e).attr("id"))})},getShardDetails:function(t){var i=this,e={collection:t};$("#"+t+" .shardProgress").html(''),$.ajax({type:"PUT",cache:!1,data:JSON.stringify(e),url:arangoHelper.databaseUrl("/_admin/cluster/collectionShardDistribution"),contentType:"application/json",processData:!1,async:!0,success:function(e){i.renderShardDetail(t,e)},error:function(e){}})},render:function(e){if("#shards"===window.location.hash&&!1===this.pending){var t=this;t.pending=!0,$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/shardDistribution"),contentType:"application/json",processData:!1,async:!0,success:function(e){var i=t.pending=!1;t.shardDistribution=e.results,_.each(e.results,function(e,t){"error"!==t&&"code"!==t&&("_"!==t.substring(0,1)&&(i=!0),(t.startsWith("_local_")||t.startsWith("_to_")||t.startsWith("_from_"))&&(i=!0))}),i?t.continueRender(e.results):arangoHelper.renderEmpty("No collections and no shards available"),t.checkActiveShardDisplay()},error:function(e){0!==e.readyState&&arangoHelper.arangoError("Cluster","Could not fetch sharding information.")}}),!1!==e&&arangoHelper.buildNodesSubNav("Shards")}},moveShardFollowers:function(e){var t=$(e.currentTarget).html();this.moveShard(e,t)},moveShard:function(e,t){var i,n,o,a,r=this,s=window.App.currentDB.get("name");n=$(e.currentTarget).parent().parent().attr("collection"),o=$(e.currentTarget).parent().parent().attr("shard"),i=t?(a=$(e.currentTarget).parent().parent().attr("leader"),a=arangoHelper.getDatabaseServerId(a),arangoHelper.getDatabaseServerId(t)):(i=$(e.currentTarget).parent().parent().attr("leader"),arangoHelper.getDatabaseServerId(i));var l=[],c=[],d={},u=[];r.dbServers[0].fetch({success:function(){r.dbServers[0].each(function(e){e.get("id")!==i&&(d[e.get("name")]={value:e.get("id"),label:e.get("name")})}),_.each(r.shardDistribution[n].Plan[o].followers,function(e){delete d[e]}),t&&delete d[arangoHelper.getDatabaseShortName(a)],_.each(d,function(e){u.push(e)}),0!==(u=u.reverse()).length?(c.push(window.modalView.createSelectEntry("toDBServer","Destination",void 0,"Please select the target database server. The selected database server will be the new leader of the shard.",u)),l.push(window.modalView.createSuccessButton("Move",r.confirmMoveShards.bind(this,s,n,o,i))),window.modalView.show("modalTable.ejs","Move shard: "+o,l,c)):arangoHelper.arangoMessage("Shards","No database server for moving the shard is available.")}})},confirmMoveShards:function(e,t,i,n){var o=$("#toDBServer").val(),a={database:e,collection:t,shard:i,fromServer:n,toServer:o};$.ajax({type:"POST",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/moveShard"),contentType:"application/json",processData:!1,data:JSON.stringify(a),async:!0,success:function(e){e.id&&(arangoHelper.arangoNotification("Shard "+i+" will be moved to "+arangoHelper.getDatabaseShortName(o)+"."),window.setTimeout(function(){window.App.shardsView.render()},3e3))},error:function(){arangoHelper.arangoError("Shard "+i+" could not be moved to "+arangoHelper.getDatabaseShortName(o)+".")}}),window.modalView.hide()},rebalanceShards:function(){var t=this;$.ajax({type:"POST",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/rebalanceShards"),contentType:"application/json",processData:!1,data:JSON.stringify({}),async:!0,success:function(e){!0===e&&(window.setTimeout(function(){t.render(!1)},3e3),arangoHelper.arangoNotification("Started rebalance process."))},error:function(){arangoHelper.arangoError("Could not start rebalance process.")}}),window.modalView.hide()},continueRender:function(r){delete r.code,delete r.error,_.each(r,function(e,t){var i={Plan:{},Current:{}};if(t.startsWith("_local_")){var n=t.substr(7,t.length-1),o=["_local_"+n,"_from_"+n,"_to_"+n,n],a=0;_.each(o,function(e,t){_.each(r[o[a]].Current,function(e,t){i.Current[t]=e}),_.each(r[o[a]].Plan,function(e,t){i.Plan[t]=e}),delete r[o[a]],r[n]=i,a++})}});var t={};Object.keys(r).sort().forEach(function(e){t[e]=r[e]}),this.$el.html(this.template.render({collections:t,visible:this.visibleCollection})),1===$(".sectionShard").length&&$(".sectionHeader").first().click(),$(".innerContent").css("min-height","0px")},updateServerTime:function(){this.serverTime=(new Date).getTime()}})}(),function(){"use strict";window.ShowClusterView=Backbone.View.extend({detailEl:"#modalPlaceholder",el:"#content",defaultFrame:12e5,template:templateEngine.createTemplate("showCluster.ejs"),modal:templateEngine.createTemplate("waitModal.ejs"),detailTemplate:templateEngine.createTemplate("detailView.ejs"),events:{"change #selectDB":"updateCollections","change #selectCol":"updateShards","click .dbserver.success":"dashboard","click .coordinator.success":"dashboard"},replaceSVGs:function(){$(".svgToReplace").each(function(){var i=$(this),n=i.attr("id"),e=i.attr("src");$.get(e,function(e){var t=$(e).find("svg");t.attr("id",n).attr("class","icon").removeAttr("xmlns:a"),i.replaceWith(t)},"xml")})},updateServerTime:function(){this.serverTime=(new Date).getTime()},setShowAll:function(){this.graphShowAll=!0},resetShowAll:function(){this.graphShowAll=!1,this.renderLineChart()},initialize:function(e){this.options=e,this.interval=1e4,this.isUpdating=!1,this.timer=null,this.knownServers=[],this.graph=void 0,this.graphShowAll=!1,this.updateServerTime(),this.dygraphConfig=this.options.dygraphConfig,this.dbservers=new window.ClusterServers([],{interval:this.interval}),this.coordinators=new window.ClusterCoordinators([],{interval:this.interval}),this.documentStore=new window.ArangoDocuments,this.statisticsDescription=new window.StatisticsDescription,this.statisticsDescription.fetch({async:!1}),this.dbs=new window.ClusterDatabases([],{interval:this.interval}),this.cols=new window.ClusterCollections,this.shards=new window.ClusterShards,this.startUpdating()},listByAddress:function(t){var i=this;this.dbservers.byAddress({},function(e){i.coordinators.byAddress(e,t)})},updateCollections:function(){var i=this,n=$("#selectCol"),e=$("#selectDB").find(":selected").attr("id");if(e){var o=n.find(":selected").attr("id");n.html(""),this.cols.getList(e,function(e){_.each(_.pluck(e,"name"),function(e){n.append('")});var t=$("#"+o,n);1===t.length&&t.prop("selected",!0),i.updateShards()})}},updateShards:function(){var e=$("#selectDB").find(":selected").attr("id"),t=$("#selectCol").find(":selected").attr("id");this.shards.getList(e,t,function(e){$(".shardCounter").html("0"),_.each(e,function(e){$("#"+e.server+"Shards").html(e.shards.length)})})},updateServerStatus:function(e){function t(e,t,i){var n,o,a=i;a=(a=a.replace(/\./g,"-")).replace(/:/g,"_"),(o=$("#id"+a)).length<1||(n=o.attr("class").split(/\s+/)[1],o.attr("class",e+" "+n+" "+t),"coordinator"===e&&("success"===t?$(".button-gui",o.closest(".tile")).toggleClass("button-gui-disabled",!1):$(".button-gui",o.closest(".tile")).toggleClass("button-gui-disabled",!0)))}var i=this;this.coordinators.getStatuses(t.bind(this,"coordinator"),function(){i.dbservers.getStatuses(t.bind(i,"dbserver")),e()})},updateDBDetailList:function(){var i=this,n=$("#selectDB"),o=n.find(":selected").attr("id");n.html(""),this.dbs.getList(function(e){_.each(_.pluck(e,"name"),function(e){n.append('")});var t=$("#"+o,n);1===t.length&&t.prop("selected",!0),i.updateCollections()})},rerender:function(){var e=this;this.updateServerStatus(function(){e.getServerStatistics(function(){e.updateServerTime(),e.data=e.generatePieData(),e.renderPieChart(e.data),e.renderLineChart(),e.updateDBDetailList()})})},render:function(){this.knownServers=[],delete this.hist;var i=this;this.listByAddress(function(t){1===Object.keys(t).length?i.type="testPlan":i.type="other",i.updateDBDetailList(),i.dbs.getList(function(e){$(i.el).html(i.template.render({dbs:_.pluck(e,"name"),byAddress:t,type:i.type})),$(i.el).append(i.modal.render({})),i.replaceSVGs(),i.getServerStatistics(function(){i.data=i.generatePieData(),i.renderPieChart(i.data),i.renderLineChart(),i.updateDBDetailList(),i.startUpdating()})})})},generatePieData:function(){var t=[],i=this;return this.data.forEach(function(e){t.push({key:e.get("name"),value:e.get("system").virtualSize,time:i.serverTime})}),t},addStatisticsItem:function(e,t,i,n){var o=this;o.hasOwnProperty("hist")||(o.hist={}),o.hist.hasOwnProperty(e)||(o.hist[e]=[]);var a=o.hist[e],r=a.length;if(0===r)a.push({time:t,snap:n,requests:i,requestsPerSecond:0});else{var s=a[r-1].time,l=a[r-1].requests;if(l";return t&&(n+=''),i&&(n+=''+i.toUpperCase()+""),n+=""}$(this.el).html(this.template.render({})),$(this.el).show(),this.typeahead="aql"===i?$("#spotlight .typeahead").typeahead({hint:!0,highlight:!0,minLength:1},{name:"Functions",source:n.substringMatcher(n.aqlBuiltinFunctionsArray),limit:n.displayLimit,templates:{header:e("Functions","fa-code","aql")}},{name:"Keywords",source:n.substringMatcher(n.aqlKeywordsArray),limit:n.displayLimit,templates:{header:e("Keywords","fa-code","aql")}},{name:"Documents",source:n.substringMatcher(n.collections.doc),limit:n.displayLimit,templates:{header:e("Documents","fa-file-text-o","Collection")}},{name:"Edges",source:n.substringMatcher(n.collections.edge),limit:n.displayLimit,templates:{header:e("Edges","fa-share-alt","Collection")}},{name:"System",limit:n.displayLimit,source:n.substringMatcher(n.collections.system),templates:{header:e("System","fa-cogs","Collection")}}):$("#spotlight .typeahead").typeahead({hint:!0,highlight:!0,minLength:1},{name:"Documents",source:n.substringMatcher(n.collections.doc),limit:n.displayLimit,templates:{header:e("Documents","fa-file-text-o","Collection")}},{name:"Edges",source:n.substringMatcher(n.collections.edge),limit:n.displayLimit,templates:{header:e("Edges","fa-share-alt","Collection")}},{name:"System",limit:n.displayLimit,source:n.substringMatcher(n.collections.system),templates:{header:e("System","fa-cogs","Collection")}}),$("#spotlight .typeahead").focus()}.bind(this);0===n.aqlBuiltinFunctionsArray.length?this.fetchKeywords(o):o()}})}(),function(){"use strict";window.StatisticBarView=Backbone.View.extend({el:"#statisticBar",events:{"change #arangoCollectionSelect":"navigateBySelect","click .tab":"navigateByTab"},template:templateEngine.createTemplate("statisticBarView.ejs"),initialize:function(e){this.currentDB=e.currentDB},replaceSVG:function(i){var n=i.attr("id"),o=i.attr("class"),e=i.attr("src");$.get(e,function(e){var t=$(e).find("svg");void 0===n&&(t=t.attr("id",n)),void 0===o&&(t=t.attr("class",o+" replaced-svg")),t=t.removeAttr("xmlns:a"),i.replaceWith(t)},"xml")},render:function(){var e=this;return $(this.el).html(this.template.render({isSystem:this.currentDB.get("isSystem")})),$("img.svg").each(function(){e.replaceSVG($(this))}),this},navigateBySelect:function(){var e=$("#arangoCollectionSelect").find("option:selected").val();window.App.navigate(e,{trigger:!0})},navigateByTab:function(e){var t=(e.target||e.srcElement).id;return"links"===t?$("#link_dropdown").slideToggle(200):"tools"===t?$("#tools_dropdown").slideToggle(200):window.App.navigate(t,{trigger:!0}),void e.preventDefault()},handleSelectNavigation:function(){$("#arangoCollectionSelect").change(function(){var e=$(this).find("option:selected").val();window.App.navigate(e,{trigger:!0})})},selectMenuItem:function(e){$(".navlist li").removeClass("active"),e&&$("."+e).addClass("active")}})}(),function(){"use strict";window.StoreDetailView=Backbone.View.extend({el:"#content",divs:["#readme","#swagger","#app-info","#sideinformation","#information","#settings"],navs:["#service-info","#service-api","#service-readme","#service-settings"],template:templateEngine.createTemplate("storeDetailView.ejs"),remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},events:{"click #installService":"installService"},installService:function(){arangoHelper.createMountPointModal(this.installFoxxFromStore.bind(this))},installCallback:function(e){window.App.navigate("#services",{trigger:!0}),window.App.applicationsView.installCallback(e)},installFoxxFromStore:function(e){var t,i;window.modalView.modalTestAll()&&(this._upgrade?(t=this.mount,i=$("#new-app-teardown").prop("checked")):"/"!==(t=window.arangoHelper.escapeHtml($("#new-app-mount").val())).charAt(0)&&(t="/"+t),void 0!==i?this.collection.installFromStore({name:this.model.get("name"),version:this.model.get("latestVersion")},t,this.installCallback.bind(this),i):this.collection.installFromStore({name:this.model.get("name"),version:this.model.get("latestVersion")},t,this.installCallback.bind(this)),window.modalView.hide(),arangoHelper.arangoNotification("Services","Installing "+this.model.get("name")+"."))},resize:function(e){e?$(".innerContent").css("height","auto"):$(".innerContent").height($(".centralRow").height()-150)},render:function(){var n=this;return this.model.fetchThumbnail(function(e){var t=function(e,t){if(e)arangoHelper.arangoError("DB","Could not get current database");else{var i=this.model.get("defaultThumbnailUrl");if(this.model.get("manifest"))try{this.model.get("manifest").thumbnail&&(i=this.model.getThumbnailUrl())}catch(e){}$(this.el).html(this.template.render({app:this.model,baseUrl:arangoHelper.databaseUrl("",t),installed:!0,image:i})),this.model.fetchReadme(n.renderReadme)}this.breadcrumb()}.bind(this);arangoHelper.currentDatabase(t),_.isEmpty(this.model.get("config"))&&$("#service-settings").attr("disabled",!0)}.bind(this)),this.resize(!1),$(this.el)},renderReadme:function(e){var t=marked(e);$("#readme").html(t)},breadcrumb:function(){var e="Service: "+this.model.get("name")+'',t='
"),$("#subNavigationBar .breadcrumb").html(e)},openApp:function(){var e=function(e,t){e?arangoHelper.arangoError("DB","Could not get current database"):window.open(this.appUrl(t),this.model.get("title")).focus()}.bind(this);arangoHelper.currentDatabase(e)},deleteApp:function(){var e=[window.modalView.createDeleteButton("Delete",function(){var e={teardown:$("#app_delete_run_teardown").is(":checked")};this.model.destroy(e,function(e,t){e||!1!==t.error||(window.modalView.hide(),window.App.navigate("services",{trigger:!0}))})}.bind(this))],t=[window.modalView.createCheckboxEntry("app_delete_run_teardown","Run teardown?",!0,"Should this app's teardown script be executed before removing the app?",!0)];window.modalView.show("modalTable.ejs",'Delete Foxx App mounted at "'+this.model.get("mount")+'"',e,t,void 0,"
'),$("new-smart-val-attr").unbind("keyup"),$("#new-smart-val-attr").on("keyup",function(e){$("#new-document-key-prefix-attr").val($(e.currentTarget).val())})):this.collection.getSmartGraphAttribute()?(n.push(this.createDocumentKeyInput(!1)),n.push(window.modalView.createTextEntry("new-smartGraph-val-attr","SmartGraph Value ("+this.collection.getSmartGraphAttribute()+")",void 0,"This smartGraphAttribute can be populated for all documents in the collection and then contain a string value. Otherwise it will be null.","",!1,[{rule:Joi.string().allow("").optional(),msg:""}])),i.push(window.modalView.createSuccessButton("Create",this.addSmartGraphDocument.bind(this))),window.modalView.show("modalTable.ejs","Create document",i,n),$("#new-document-key-attr").css("width","50%").css("float","right"),$("#new-document-key-attr").before('
:
'),$("#new-smartGraph-val-attr").unbind("keyup"),$("#new-smartGraph-val-attr").on("keyup",function(e){$("#new-document-key-prefix-attr").val($(e.currentTarget).val())})):"edge"===t?(n.push(window.modalView.createTextEntry("new-edge-from-attr","_from","","document _id: document handle of the linked vertex (incoming relation)",void 0,!1,[{rule:Joi.string().required(),msg:"No _from attribute given."}])),n.push(window.modalView.createTextEntry("new-edge-to","_to","","document _id: document handle of the linked vertex (outgoing relation)",void 0,!1,[{rule:Joi.string().required(),msg:"No _to attribute given."}])),n.push(window.modalView.createTextEntry("new-edge-key-attr","_key",void 0,"the edges unique key(optional attribute, leave empty for autogenerated key","is optional: leave empty for autogenerated key",!1,[{rule:Joi.string().allow("").optional(),msg:""}])),i.push(window.modalView.createSuccessButton("Create",this.addEdge.bind(this))),window.modalView.show("modalTable.ejs","Create edge",i,n)):(n.push(this.createDocumentKeyInput(!1)),i.push(window.modalView.createSuccessButton("Create",this.addDocument.bind(this))),window.modalView.show("modalTable.ejs","Create document",i,n))}.bind(this);arangoHelper.collectionApiType(t,!0,o)}},createDocumentKeyInput:function(e){var t="leave empty for autogenerated key",i="the documents unique key";return e?t="":i+=" (optional attribute, leave empty for autogenerated key",window.modalView.createTextEntry("new-document-key-attr","_key",void 0,i,t,e||!1,[{rule:Joi.string().allow("").optional(),msg:""}])},addEdge:function(){var e=window.location.hash.split("/")[1],t=$(".modal-body #new-edge-from-attr").last().val(),i=$(".modal-body #new-edge-to").last().val(),n=$(".modal-body #new-edge-key-attr").last().val();""!==n||void 0!==n?this.documentStore.createTypeEdge(e,t,i,n,this.goToDocument):this.documentStore.createTypeEdge(e,t,i,null,this.goToDocument)},addDocument:function(){var e=window.location.hash.split("/")[1],t=$(".modal-body #new-document-key-attr").last().val();""!==t||void 0!==t?this.documentStore.createTypeDocument(e,t,this.goToDocument):this.documentStore.createTypeDocument(e,null,this.goToDocument)},addSmartAttributeDocument:function(){var e=window.location.hash.split("/")[1],t=$(".modal-body #new-document-key-attr").last().val(),i=$(".modal-body #new-smart-val-attr").last().val();""!==t||void 0!==t?this.documentStore.createTypeDocument(e,t,this.goToDocument,!1,this.collection.getSmartJoinAttribute(),i,null,null):this.documentStore.createTypeDocument(e,null,this.goToDocument,!1,this.collection.getSmartJoinAttribute(),i,null,null)},addSmartGraphDocument:function(){var e=window.location.hash.split("/")[1],t=$(".modal-body #new-document-key-attr").last().val(),i=$(".modal-body #new-smartGraph-val-attr").last().val();""===i&&(i=null);var n=null;this.collection.getSmartGraphAttribute()&&(n=this.collection.getSmartGraphAttribute()),""===t&&(t=null),this.documentStore.createTypeDocument(e,t,this.goToDocument,!1,null,null,n,i)},goToDocument:function(e,t,i){if(e)arangoHelper.arangoError("Error",i.errorMessage);else{var n;window.modalView.hide(),t=t.split("/");try{n="collection/"+t[0]+"/"+t[1],decodeURI(n)}catch(e){n="collection/"+t[0]+"/"+encodeURIComponent(t[1])}window.location.hash=n}},moveSelectedDocs:function(){var e=[],t=[];0!==this.getSelectedDocs().length?(t.push(window.modalView.createTextEntry("move-documents-to","Move to","",!1,"collection-name",!0,[{rule:Joi.string().regex(/^[a-zA-Z]/),msg:"Collection name must always start with a letter."},{rule:Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),msg:'Only Symbols "_" and "-" are allowed.'},{rule:Joi.string().required(),msg:"No collection name given."}])),e.push(window.modalView.createSuccessButton("Move",this.confirmMoveSelectedDocs.bind(this))),window.modalView.show("modalTable.ejs","Move documents",e,t)):arangoHelper.arangoMessage("Move documents","No documents selected!")},confirmMoveSelectedDocs:function(){var e=this.getSelectedDocs(),t=this,i=$("#move-documents-to").val(),n=function(e){e?arangoHelper.arangoError("Error","Could not move document."):(t.collection.setTotalMinusOne(),this.collection.getDocuments(this.getDocsCallback.bind(this)),$("#markDocuments").click(),window.modalView.hide())}.bind(this);_.each(e,function(e){t.collection.moveDocument(e,t.collection.collectionID,i,n)})},deleteSelectedDocs:function(){var e=[],t=[],i=this.getSelectedDocs();0!==i.length?(t.push(window.modalView.createReadOnlyEntry(void 0,i.length+" documents selected","Do you want to delete all selected documents?",void 0,void 0,!1,void 0)),e.push(window.modalView.createDeleteButton("Delete",this.confirmDeleteSelectedDocs.bind(this))),window.modalView.show("modalTable.ejs","Delete documents",e,t)):arangoHelper.arangoMessage("Delete documents","No documents selected!")},confirmDeleteSelectedDocs:function(){var e=this.getSelectedDocs(),n=[],o=this;_.each(e,function(e){if("document"===o.type){var t=function(e){e?(n.push(!1),arangoHelper.arangoError("Document error","Could not delete document.")):(n.push(!0),o.collection.setTotalMinusOne(),o.collection.getDocuments(this.getDocsCallback.bind(this)),$("#markDocuments").click(),window.modalView.hide())}.bind(o);o.documentStore.deleteDocument(o.collection.collectionID,e,t)}else if("edge"===o.type){var i=function(e){e?(n.push(!1),arangoHelper.arangoError("Edge error","Could not delete edge")):(o.collection.setTotalMinusOne(),n.push(!0),o.collection.getDocuments(this.getDocsCallback.bind(this)),$("#markDocuments").click(),window.modalView.hide())}.bind(o);o.documentStore.deleteEdge(o.collection.collectionID,e,i)}})},getSelectedDocs:function(){var t=[];return _.each($("#docPureTable .pure-table-body .pure-table-row"),function(e){$(e).hasClass("selected-row")&&t.push($($(e).children()[1]).find(".key").text())}),t},remove:function(e){$(e.currentTarget).hasClass("disabled")||(this.docid=$(e.currentTarget).parent().parent().prev().find(".key").text(),$("#confirmDeleteBtn").attr("disabled",!1),$("#docDeleteModal").modal("show"))},confirmDelete:function(){$("#confirmDeleteBtn").attr("disabled",!0),"source"!==window.location.hash.split("/")[3]&&this.reallyDelete()},reallyDelete:function(){if("document"===this.type){var e=function(e){e?arangoHelper.arangoError("Error","Could not delete document"):(this.collection.setTotalMinusOne(),this.collection.getDocuments(this.getDocsCallback.bind(this)),$("#docDeleteModal").modal("hide"))}.bind(this);this.documentStore.deleteDocument(this.collection.collectionID,this.docid,e)}else if("edge"===this.type){var t=function(e){e?arangoHelper.arangoError("Edge error","Could not delete edge"):(this.collection.setTotalMinusOne(),this.collection.getDocuments(this.getDocsCallback.bind(this)),$("#docDeleteModal").modal("hide"))}.bind(this);this.documentStore.deleteEdge(this.collection.collectionID,this.docid,t)}},editModeClick:function(e){var t=$(e.currentTarget);t.hasClass("selected-row")?t.removeClass("selected-row"):t.addClass("selected-row");var i=this.getSelectedDocs();$(".selectedCount").text(i.length),_.each(this.editButtons,function(e){0'),e=$("#totalDocuments")),"document"===this.type&&e.html(numeral(this.collection.getTotal()).format("0,0")+" doc(s)"),"edge"===this.type&&e.html(numeral(this.collection.getTotal()).format("0,0")+" edge(s)"),this.collection.getTotal()>this.collection.MAX_SORT?($("#docsSort").attr("disabled",!0),$("#docsSort").attr("placeholder","Sort limit reached (docs count)")):($("#docsSort").attr("disabled",!1),$("#docsSort").attr("placeholder","Sort by attribute"))},breadcrumb:function(){var e=this;window.App.naviView&&void 0!==$("#subNavigationBar .breadcrumb").html()?($("#subNavigationBar .breadcrumb").html("Collection: "+arangoHelper.escapeHtml(this.collectionName)),arangoHelper.buildCollectionSubNav(this.collectionName,"Content")):window.setTimeout(function(){e.breadcrumb()},100)}})}(),function(){"use strict";function l(e){var t=e.split("/");return"collection/"+encodeURIComponent(t[0])+"/"+encodeURIComponent(t[1])}window.DocumentView=Backbone.View.extend({el:"#content",readOnly:!1,colid:0,docid:0,customView:!1,defaultMode:"tree",template:templateEngine.createTemplate("documentView.ejs"),events:{"click #saveDocumentButton":"saveDocument","click #deleteDocumentButton":"deleteDocumentModal","click #confirmDeleteDocument":"deleteDocument","click #document-from":"navigateToDocument","click #document-to":"navigateToDocument","keydown #documentEditor .ace_editor":"keyPress","keyup .jsoneditor .search input":"checkSearchBox","click #addDocument":"addDocument"},remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},checkSearchBox:function(e){""===$(e.currentTarget).val()&&this.editor.expandAll()},initialize:function(){var e=localStorage.getItem("JSONEditorMode");e&&(this.defaultMode=e)},addDocument:function(e){this.readOnly||window.App.documentsView.addDocumentModal(e)},storeMode:function(e){localStorage.setItem("JSONEditorMode",e),this.defaultMode=e,this.editor.setMode(this.defaultMode)},keyPress:function(e){e.ctrlKey&&13===e.keyCode?(e.preventDefault(),this.saveDocument()):e.metaKey&&13===e.keyCode&&(e.preventDefault(),this.saveDocument())},editor:0,setType:function(){var n=this,e=function(e,t,i){e?(arangoHelper.arangoError("Error","Document not found."),n.renderNotFound(i)):(this.type=i,this.breadcrumb(),this.fillInfo(),this.fillEditor(),arangoHelper.checkCollectionPermissions(this.colid,this.changeViewToReadOnly.bind(this)))}.bind(this);this.collection.getDocument(this.colid,this.docid,e)},renderNotFound:function(e){$(".document-info-div").remove(),$(".headerButton").remove(),$(".document-content-div").html('
')},calculateEdgeDefinitionMap:function(){var t={};return this.collection.models.forEach(function(e){e.get("edgeDefinitions").forEach(function(e){t[e.collection]={from:e.from,to:e.to}})}),t}})}(),function(){"use strict";window.GraphSettingsView=Backbone.View.extend({el:"#graphSettingsContent",remove:function(){return this.$el.empty().off(),this.stopListening(),this},general:{graph:{type:"divider",name:"Graph"},nodeStart:{type:"string",name:"Startnode",desc:"A valid node id or space seperated list of id's. If empty, a random node will be chosen.",value:2},layout:{type:"select",name:"Layout",desc:"Different graph algorithms. No overlap is very fast (more than 5000 nodes), force is slower (less than 5000 nodes) and fruchtermann is the slowest (less than 500 nodes).",noverlap:{name:"No overlap",val:"noverlap"},force:{name:"Force",val:"force"},fruchtermann:{name:"Fruchtermann",val:"fruchtermann"}},renderer:{type:"select",name:"Renderer",desc:"Canvas enables editing, WebGL is only for displaying a graph but much faster.",canvas:{name:"Canvas",val:"canvas"},webgl:{name:"WebGL (experimental)",val:"webgl"}},depth:{desc:"Search depth, starting from your start node.",type:"number",name:"Search Depth",value:2},limit:{desc:"Limit nodes count. If empty or zero, no limit is set.",type:"number",name:"Limit",value:250}},specific:{nodes:{type:"divider",name:"Nodes"},nodeLabel:{type:"string",name:"Label",desc:"Node label. Please choose a valid and available node attribute.",default:"_key"},nodeLabelByCollection:{type:"select",name:"Add Collection Name",desc:"Append collection name to the label?",yes:{name:"Yes",val:"true"},no:{name:"No",val:"false"}},nodeColorByCollection:{type:"select",name:"Color By Collections",no:{name:"No",val:"false"},yes:{name:"Yes",val:"true"},desc:"Should nodes be colorized by their collection? If enabled, node color and node color attribute will be ignored."},nodeColor:{type:"color",name:"Color",desc:"Default node color. RGB or HEX value.",default:"#2ecc71"},nodeColorAttribute:{type:"string",name:"Color Attribute",desc:"If an attribute is given, nodes will then be colorized by the attribute. This setting ignores default node color if set."},nodeSizeByEdges:{type:"select",name:"Size By Connections",yes:{name:"Yes",val:"true"},no:{name:"No",val:"false"},desc:"Should nodes be sized by their edges count? If enabled, node sizing attribute will be ignored."},nodeSize:{type:"string",name:"Sizing Attribute",desc:"Default node size. Numeric value > 0."},edges:{type:"divider",name:"Edges"},edgeLabel:{type:"string",name:"Label",desc:"Default edge label."},edgeLabelByCollection:{type:"select",name:"Add Collection Name",desc:"Set label text by collection. If activated edge label attribute will be ignored.",yes:{name:"Yes",val:"true"},no:{name:"No",val:"false"}},edgeColorByCollection:{type:"select",name:"Color By Collections",no:{name:"No",val:"false"},yes:{name:"Yes",val:"true"},desc:"Should edges be colorized by their collection? If enabled, edge color and edge color attribute will be ignored."},edgeColor:{type:"color",name:"Color",desc:"Default edge color. RGB or HEX value.",default:"#cccccc"},edgeColorAttribute:{type:"string",name:"Color Attribute",desc:"If an attribute is given, edges will then be colorized by the attribute. This setting ignores default edge color if set."},edgeEditable:{type:"select",hide:"true",name:"Editable",yes:{name:"Yes",val:"true"},no:{name:"No",val:"false"},desc:"Should edges be editable?"},edgeType:{type:"select",name:"Type",desc:"The type of the edge",line:{name:"Line",val:"line"},arrow:{name:"Arrow",val:"arrow"},curve:{name:"Curve",val:"curve"},dotted:{name:"Dotted",val:"dotted"},dashed:{name:"Dashed",val:"dashed"},tapered:{name:"Tapered",val:"tapered"}}},template:templateEngine.createTemplate("graphSettingsView.ejs"),initialize:function(e){this.name=e.name,this.userConfig=e.userConfig,this.saveCallback=e.saveCallback,e.noDefinedGraph&&(this.noDefinedGraph=e.noDefinedGraph)},events:{"click #saveGraphSettings":"saveGraphSettings","click #restoreGraphSettings":"setDefaults","keyup #graphSettingsView input":"checkEnterKey","keyup #graphSettingsView select":"checkEnterKey",'change input[type="range"]':"saveGraphSettings",'change input[type="color"]':"checkColor","change select":"saveGraphSettings","focus #graphSettingsView input":"lastFocus","focus #graphSettingsView select":"lastFocus",'focusout #graphSettingsView input[type="text"]':"checkinput"},lastFocus:function(e){this.lastFocussed=e.currentTarget.id,this.lastFocussedValue=$(e.currentTarget).val()},checkinput:function(e){500Fetching graph data. Please wait ... If it`s taking too much time to draw the graph, please navigate to: Graphs ViewClick the settings icon and reset the display settings.It is possible that the graph is too big to be handled by the browser.');function i(){var e={};n.graphConfig&&(delete(e=_.clone(n.graphConfig)).layout,delete e.edgeType,delete e.renderer),n.tmpStartNode&&(n.graphConfig?0===n.graphConfig.nodeStart.length&&(e.nodeStart=n.tmpStartNode):e.nodeStart=n.tmpStartNode),n.setupSigma(),n.fetchStarted=new Date,$.ajax({type:"GET",url:arangoHelper.databaseUrl("/_admin/aardvark/graph/"+encodeURIComponent(n.name)),contentType:"application/json",data:e,success:function(e){!0===e.empty?n.renderGraph(e,t):(e.settings&&e.settings.startVertex&&void 0===n.graphConfig.startNode&&void 0===n.tmpStartNode&&(n.tmpStartNode=e.settings.startVertex._id),n.fetchFinished=new Date,n.calcStart=n.fetchFinished,$("#calcText").html("Server response took "+Math.abs(n.fetchFinished.getTime()-n.fetchStarted.getTime())+" ms. Initializing graph engine. Please wait ... "),window.setTimeout(function(){n.renderGraph(e,t)},50))},error:function(e){try{var t;if(e.responseJSON.exception)if(t=e.responseJSON.exception,-1!==e.responseJSON.exception.search("1205")){var i='Starting point: '+n.graphConfig.nodeStart+" is invalid";$("#calculatingGraph").html('
'),r.startLayout();var p=250;e.nodes&&(p=e.nodes.length,i?p<250?p=250:p+=500:(p<=250&&(p=500),p+=500)),e.empty&&arangoHelper.arangoNotification("Graph","Your graph is empty. Click inside the white window to create your first node."),window.setTimeout(function(){r.stopLayout()},p)}else"fruchtermann"===r.algorithm&&sigma.layouts.fruchtermanReingold.start(c);"force"!==r.algorithm&&r.reInitDragListener(),document.getElementsByClassName("sigma-mouse")[0].addEventListener("mousemove",r.trackCursorPosition.bind(this),!1),t&&($("#"+t).focus(),$("#graphSettingsContent").animate({scrollTop:$("#"+t).offset().top},2e3)),$("#calculatingGraph").fadeOut("slow"),i||r.graphConfig&&r.graphConfig.nodeSizeByEdges,r.calcFinished=new Date,!0===e.empty&&$(".sigma-background").before('The graph is empty. Please right-click to add a node.'),!0===r.graphNotInitialized&&(r.updateColors(r.tmpGraphArray),r.graphNotInitialized=!1,r.tmpGraphArray=[]),"force"===r.algorithm?$("#toggleForce").fadeIn("fast"):$("#toggleForce").fadeOut("fast")},reInitDragListener:function(){var t=this;void 0!==this.dragListener&&(sigma.plugins.killDragNodes(this.currentGraph),this.dragListener={}),this.dragListener=sigma.plugins.dragNodes(this.currentGraph,this.currentGraph.renderers[0]),this.dragListener.bind("drag",function(e){t.dragging=!0}),this.dragListener.bind("drop",function(e){window.setTimeout(function(){t.dragging=!1},400)})},keyUpFunction:function(e){switch(e.keyCode){case 76:e.altKey&&this.toggleLasso()}},toggleLayout:function(){this.layouting?this.stopLayout():this.startLayout()},startLayout:function(e,t){var i=this;this.currentGraph.settings("drawLabels",!1),this.currentGraph.settings("drawEdgeLabels",!1),sigma.plugins.killDragNodes(this.currentGraph),!0===e&&(this.currentGraph.killForceAtlas2(),window.setTimeout(function(){i.stopLayout(),t&&i.currentGraph.refresh({skipIndexation:!0})},500)),$("#toggleForce .fa").removeClass("fa-play").addClass("fa-pause"),$("#toggleForce span").html("Stop layout"),this.layouting=!0,this.aqlMode,this.currentGraph.startForceAtlas2({worker:!0})},stopLayout:function(){$("#toggleForce .fa").removeClass("fa-pause").addClass("fa-play"),$("#toggleForce span").html("Resume layout"),this.layouting=!1,this.currentGraph.stopForceAtlas2(),this.currentGraph.settings("drawLabels",!0),this.currentGraph.settings("drawEdgeLabels",!0),this.currentGraph.refresh({skipIndexation:!0}),this.reInitDragListener()}})}(),function(){"use strict";window.HelpUsView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("helpUsView.ejs"),render:function(){this.$el.html(this.template.render({}))}})}(),function(){"use strict";window.IndicesView=Backbone.View.extend({el:"#content",initialize:function(e){var t=this;this.collectionName=e.collectionName,this.model=this.collection,t.interval=window.setInterval(function(){-1!==window.location.hash.indexOf("cIndices/"+t.collectionName)&&window.VISIBLE&&$("#collectionEditIndexTable").is(":visible")&&!$("#indexDeleteModal").is(":visible")&&t.rerender()},t.refreshRate)},interval:null,refreshRate:1e4,template:templateEngine.createTemplate("indicesView.ejs"),events:{},remove:function(){return this.interval&&window.clearInterval(this.interval),this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},render:function(){function t(e){var t=e.supports.aliases;t=t?t.indexes:{},$(i.el).html(i.template.render({model:i.model,supported:e.supports.indexes.filter(function(e){return!t.hasOwnProperty(e)})})),i.breadcrumb(),window.arangoHelper.buildCollectionSubNav(i.collectionName,"Indexes"),i.getIndex(),arangoHelper.checkCollectionPermissions(i.collectionName,i.changeViewToReadOnly)}var i=this;this.engineData?t(this.engineData):$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/engine"),contentType:"application/json",processData:!1,success:function(e){i.engineData=e,t(e)},error:function(){arangoHelper.arangoNotification("Index","Could not fetch index information.")}})},rerender:function(){this.getIndex(!0)},changeViewToReadOnly:function(){$(".breadcrumb").html($(".breadcrumb").html()+" (read-only)"),$("#addIndex").addClass("disabled"),$("#addIndex").css("color","rgba(0,0,0,.5)"),$("#addIndex").css("cursor","not-allowed")},breadcrumb:function(){$("#subNavigationBar .breadcrumb").html("Collection: "+this.collectionName)},getIndex:function(n){var e=function(e,t,i){e?window.arangoHelper.arangoError("Index",t.errorMessage):this.renderIndex(t,i,n)}.bind(this);this.model.getIndex(e)},createIndex:function(){var e,t,i,n,o,a,r=this,s={};switch($("#newIndexType").val()){case"Ttl":e=$("#newTtlFields").val();var l=parseInt($("#newTtlExpireAfter").val(),10)||0;o=r.checkboxToValue("#newTtlBackground"),a=$("#newTtlName").val(),s={type:"ttl",fields:r.stringToArray(e),expireAfter:l,inBackground:o,name:a};break;case"Geo":e=$("#newGeoFields").val(),o=r.checkboxToValue("#newGeoBackground");var c=r.checkboxToValue("#newGeoJson");a=$("#newGeoName").val(),s={type:"geo",fields:r.stringToArray(e),geoJson:c,inBackground:o,name:a};break;case"Persistent":e=$("#newPersistentFields").val(),t=r.checkboxToValue("#newPersistentUnique"),i=r.checkboxToValue("#newPersistentSparse"),n=r.checkboxToValue("#newPersistentDeduplicate"),o=r.checkboxToValue("#newPersistentBackground"),a=$("#newPersistentName").val(),s={type:"persistent",fields:r.stringToArray(e),unique:t,sparse:i,deduplicate:n,inBackground:o,name:a};break;case"Hash":e=$("#newHashFields").val(),t=r.checkboxToValue("#newHashUnique"),i=r.checkboxToValue("#newHashSparse"),n=r.checkboxToValue("#newHashDeduplicate"),o=r.checkboxToValue("#newHashBackground"),a=$("#newHashName").val(),s={type:"hash",fields:r.stringToArray(e),unique:t,sparse:i,deduplicate:n,inBackground:o,name:a};break;case"Fulltext":e=$("#newFulltextFields").val();var d=parseInt($("#newFulltextMinLength").val(),10)||0;o=r.checkboxToValue("#newFulltextBackground"),a=$("#newFulltextName").val(),s={type:"fulltext",fields:r.stringToArray(e),minLength:d,inBackground:o,name:a};break;case"Skiplist":e=$("#newSkiplistFields").val(),t=r.checkboxToValue("#newSkiplistUnique"),i=r.checkboxToValue("#newSkiplistSparse"),n=r.checkboxToValue("#newSkiplistDeduplicate"),o=r.checkboxToValue("#newSkiplistBackground"),a=$("#newSkiplistName").val(),s={type:"skiplist",fields:r.stringToArray(e),unique:t,sparse:i,deduplicate:n,inBackground:o,name:a}}this.model.createIndex(s,function(e,t){if(e)if(t){var i=JSON.parse(t.responseText);arangoHelper.arangoError("Index error",i.errorMessage)}else arangoHelper.arangoError("Index error","Could not create index.");else arangoHelper.arangoNotification("Index","Creation in progress. This may take a while.");r.toggleNewIndexView(),r.render()})},bindIndexEvents:function(){this.unbindIndexEvents();var t=this;$("#indexEditView #addIndex").bind("click",function(){t.toggleNewIndexView(),$("#cancelIndex").unbind("click"),$("#cancelIndex").bind("click",function(){t.toggleNewIndexView(),t.render()}),$("#createIndex").unbind("click"),$("#createIndex").bind("click",function(){t.createIndex()})}),$("#newIndexType").bind("change",function(){t.selectIndexType()}),$(".deleteIndex").bind("click",function(e){t.prepDeleteIndex(e)}),$("#infoTab a").bind("click",function(e){if($("#indexDeleteModal").remove(),"Indexes"!==$(e.currentTarget).html()||$(e.currentTarget).parent().hasClass("active")||($("#newIndexView").hide(),$("#indexEditView").show(),$("#indexHeaderContent #modal-dialog .modal-footer .button-danger").hide(),$("#indexHeaderContent #modal-dialog .modal-footer .button-success").hide(),$("#indexHeaderContent #modal-dialog .modal-footer .button-notification").hide()),"General"===$(e.currentTarget).html()&&!$(e.currentTarget).parent().hasClass("active")){$("#indexHeaderContent #modal-dialog .modal-footer .button-danger").show(),$("#indexHeaderContent #modal-dialog .modal-footer .button-success").show(),$("#indexHeaderContent #modal-dialog .modal-footer .button-notification").show();var t=$(".index-button-bar2")[0];$("#cancelIndex").is(":visible")&&($("#cancelIndex").detach().appendTo(t),$("#createIndex").detach().appendTo(t))}})},prepDeleteIndex:function(e){var t=this;this.lastTarget=e,this.lastId=$(this.lastTarget.currentTarget).parent().parent().first().children().first().text(),$("#indexDeleteModal").length||($("#content #modal-dialog .modal-footer").after('
Really delete?
'),$("#indexHeaderContent #indexConfirmDelete").unbind("click"),$("#indexHeaderContent #indexConfirmDelete").bind("click",function(){$("#indexHeaderContent #indexDeleteModal").remove(),t.deleteIndex()}),$("#indexHeaderContent #indexAbortDelete").unbind("click"),$("#indexHeaderContent #indexAbortDelete").bind("click",function(){$("#indexHeaderContent #indexDeleteModal").remove()}))},unbindIndexEvents:function(){$("#indexHeaderContent #indexEditView #addIndex").unbind("click"),$("#indexHeaderContent #newIndexType").unbind("change"),$("#indexHeaderContent #infoTab a").unbind("click"),$("#indexHeaderContent .deleteIndex").unbind("click")},deleteIndex:function(){var e=function(e){e?(arangoHelper.arangoError("Could not delete index"),$("tr th:contains('"+this.lastId+"')").parent().children().last().html(''),this.model.set("locked",!1)):e||void 0===e||($("tr th:contains('"+this.lastId+"')").parent().remove(),this.model.set("locked",!1))}.bind(this);this.model.set("locked",!0),this.model.deleteIndex(this.lastId,e),$("tr th:contains('"+this.lastId+"')").parent().children().last().html('')},renderIndex:function(e,i,t){this.index=e;arangoHelper.getAardvarkJobs(function(e,t){if(e)arangoHelper.arangoError("Jobs","Could not read pending jobs.");else{var o=function(e,t,i){e?404===t.responseJSON.code?arangoHelper.deleteAardvarkJob(i):400===t.responseJSON.code?(arangoHelper.arangoError("Index creation failed",t.responseJSON.errorMessage),arangoHelper.deleteAardvarkJob(i)):204===t.responseJSON.code&&arangoHelper.arangoMessage("Index","There is at least one new index in the queue or in the process of being created."):arangoHelper.deleteAardvarkJob(i)};_.each(t,function(n){n.collection===i&&$.ajax({type:"PUT",cache:!1,url:arangoHelper.databaseUrl("/_api/job/"+n.id),contentType:"application/json",success:function(e,t,i){o(!1,e,n.id)},error:function(e){o(!0,e,n.id)}})})}});var r="collectionInfoTh modal-text";if(this.index){var s="",l="";t&&$("#collectionEditIndexTable tbody").empty(),_.each(this.index.indexes,function(e){l="primary"===e.type||"edge"===e.type?'':'',void 0!==e.fields&&(s=e.fields.join(", "));var t=e.id.indexOf("/"),i=e.id.substr(t+1,e.id.length),n=e.hasOwnProperty("selectivityEstimate")?(100*e.selectivityEstimate).toFixed(2)+"%":"n/a",o=e.hasOwnProperty("sparse")?e.sparse:"n/a",a=e.hasOwnProperty("deduplicate")?e.deduplicate:"n/a";$("#collectionEditIndexTable").append("
"+arangoHelper.escapeHtml(i)+"
"+arangoHelper.escapeHtml(e.type)+"
"+arangoHelper.escapeHtml(e.unique)+"
"+arangoHelper.escapeHtml(o)+"
"+arangoHelper.escapeHtml(a)+"
"+arangoHelper.escapeHtml(n)+"
"+arangoHelper.escapeHtml(s)+"
"+arangoHelper.escapeHtml(e.name)+"
"+l+"
")})}this.bindIndexEvents()},selectIndexType:function(){$(".newIndexClass").hide();var e=$("#newIndexType").val();null===e&&(e=$("#newIndexType").children().first().attr("value"),$("#newIndexType").val(arangoHelper.escapeHtml(e))),$("#newIndexType"+e).show()},resetIndexForms:function(){$("#indexHeader input").val("").prop("checked",!1),$("#newIndexType").val("unknown").prop("selected",!0),this.selectIndexType()},toggleNewIndexView:function(){if(!$("#addIndex").hasClass("disabled")){var e=$(".index-button-bar2")[0];$("#indexEditView").is(":visible")?($("#indexEditView").hide(),$("#newIndexView").show(),$("#cancelIndex").detach().appendTo("#indexHeaderContent #modal-dialog .modal-footer"),$("#createIndex").detach().appendTo("#indexHeaderContent #modal-dialog .modal-footer")):($("#indexEditView").show(),$("#newIndexView").hide(),$("#cancelIndex").detach().appendTo(e),$("#createIndex").detach().appendTo(e)),this.resetIndexForms()}arangoHelper.createTooltips(".index-tooltip")},stringToArray:function(e){var t=[];return e.split(",").forEach(function(e){""!==(e=e.replace(/(^\s+|\s+$)/g,""))&&t.push(e)}),t},checkboxToValue:function(e){return $(e).prop("checked")}})}(),function(){"use strict";window.InfoView=Backbone.View.extend({el:"#content",initialize:function(e){this.collectionName=e.collectionName,this.model=this.collection},events:{},render:function(){this.breadcrumb(),window.arangoHelper.buildCollectionSubNav(this.collectionName,"Info"),this.renderInfoView(),arangoHelper.checkCollectionPermissions(this.collectionName,this.changeViewToReadOnly)},changeViewToReadOnly:function(){$(".breadcrumb").html($(".breadcrumb").html()+" (read-only)")},breadcrumb:function(){$("#subNavigationBar .breadcrumb").html("Collection: "+this.collectionName)},renderInfoView:function(){if(this.model.get("locked"))return 0;var n=function(e,t,i){if(e)arangoHelper.arangoError("Figures","Could not get revision.");else{frontendConfig.isCluster&&0===i.figures.alive.size&&0===i.figures.alive.count&&0===i.figures.datafiles.count&&0===i.figures.datafiles.fileSize&&0===i.figures.journals.count&&0===i.figures.journals.fileSize&&0===i.figures.compactors.count&&0===i.figures.compactors.fileSize&&0===i.figures.dead.size&&0===i.figures.dead.count&&(i.walMessage=" - not ready yet - ");var n={figures:i,revision:t,model:this.model};window.modalView.show("modalCollectionInfo.ejs","Collection: "+this.model.get("name"),[],n,null,null,null,null,null,"content")}}.bind(this),e=function(e,t){if(e)arangoHelper.arangoError("Figures","Could not get figures.");else{var i=t;this.model.getRevision(n,i)}}.bind(this);this.model.getFigures(e)}})}(),function(){"use strict";window.ServiceInstallGitHubView=Backbone.View.extend({el:"#content",readOnly:!1,template:templateEngine.createTemplate("serviceInstallGitHubView.ejs"),remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},initialize:function(){window.App.replaceApp&&(this._upgrade=!0)},events:{"click #installGitHubService":"installGitHubService","keydown input":"checkValidators"},checkValidators:function(){1!==window.modalView._validators.length&&(window.modalView.clearValidators(),this.setGithubValidators())},render:function(){return $(this.el).html(this.template.render({services:this.collection,upgrade:this._upgrade})),this.breadcrumb(),this.setGithubValidators(),arangoHelper.createTooltips(".modalTooltips"),this},breadcrumb:function(){var e=this;if(window.App.naviView){var t="New";this._upgrade&&(t="Replace ("+window.App.replaceAppData.mount+")"),$("#subNavigationBar .breadcrumb").html('Services: '+t),arangoHelper.buildServicesSubNav("GitHub")}else window.setTimeout(function(){e.breadcrumb()},100)},installGitHubService:function(){arangoHelper.createMountPointModal(this.installFoxxFromGithub.bind(this))},installFoxxFromGithub:function(){if(window.modalView.modalTestAll()){var e,t,i,n,o;this._upgrade?e=window.App.replaceAppData.mount:"/"!==(e=window.arangoHelper.escapeHtml($("#new-app-mount").val())).charAt(0)&&(e="/"+e),n=window.arangoHelper.escapeHtml($("#repository").val()),""===(o=window.arangoHelper.escapeHtml($("#tag").val()))&&(o="master");try{Joi.assert(n,Joi.string().regex(/^[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+$/))}catch(e){return}t={url:n,version:o},(i=arangoHelper.getFoxxFlags()).legacy=Boolean($("#github-app-islegacy")[0].checked),this.collection.install("git",t,e,i,this.installCallback.bind(this))}},installCallback:function(e){window.App.navigate("#services",{trigger:!0}),window.App.applicationsView.installCallback(e)},setGithubValidators:function(){window.modalView.modalBindValidation({id:"repository",validateInput:function(){return[{rule:Joi.string().required().regex(/^[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+$/),msg:"No valid Github account and repository."}]}}),window.modalView.modalTestAll()}})}(),function(){"use strict";window.ServiceInstallNewView=Backbone.View.extend({el:"#content",readOnly:!1,template:templateEngine.createTemplate("serviceInstallNewView.ejs"),remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},events:{"click #installNewService":"installNewService","keydown input":"checkValidators"},checkValidators:function(){4!==window.modalView._validators.length&&(window.modalView.clearValidators(),this.setNewAppValidators())},initialize:function(){window.App.replaceApp&&(this._upgrade=!0)},render:function(){return $(this.el).html(this.template.render({services:this.collection,upgrade:this._upgrade})),this.renderSelects(),this.breadcrumb(),this.setNewAppValidators(),arangoHelper.createTooltips(".modalTooltips"),this},installNewService:function(){arangoHelper.createMountPointModal(this.generateNewFoxxApp.bind(this))},generateNewFoxxApp:function(){var e,t,i;window.modalView.modalTestAll()&&(this._upgrade?e=window.App.replaceAppData.mount:"/"!==(e=window.arangoHelper.escapeHtml($("#new-app-mount").val())).charAt(0)&&(e="/"+e),t={name:window.arangoHelper.escapeHtml($("#new-app-name").val()),documentCollections:_.map($("#new-app-document-collections").select2("data"),function(e){return window.arangoHelper.escapeHtml(e.text)}),edgeCollections:_.map($("#new-app-edge-collections").select2("data"),function(e){return window.arangoHelper.escapeHtml(e.text)}),author:window.arangoHelper.escapeHtml($("#new-app-author").val()),license:window.arangoHelper.escapeHtml($("#new-app-license").val()),description:window.arangoHelper.escapeHtml($("#new-app-description").val())},i=arangoHelper.getFoxxFlags(),this.collection.install("generate",t,e,i,this.installCallback.bind(this)));window.modalView.hide()},checkValidation:function(){window.modalView.modalTestAll()},installCallback:function(e){window.App.navigate("#services",{trigger:!0}),window.App.applicationsView.installCallback(e)},renderSelects:function(){$("#new-app-document-collections").select2({tags:[],showSearchBox:!1,minimumResultsForSearch:-1,width:"336px"}),$("#new-app-edge-collections").select2({tags:[],showSearchBox:!1,minimumResultsForSearch:-1,width:"336px"})},setNewAppValidators:function(){window.modalView.modalBindValidation({id:"new-app-author",validateInput:function(){return[{rule:Joi.string().required().min(1),msg:"Has to be non empty."}]}}),window.modalView.modalBindValidation({id:"new-app-name",validateInput:function(){return[{rule:Joi.string().required().regex(/^[a-zA-Z\-_][a-zA-Z0-9\-_]*$/),msg:"Can only contain a to z, A to Z, 0-9, '-' and '_'. Cannot start with a number."}]}}),window.modalView.modalBindValidation({id:"new-app-description",validateInput:function(){return[{rule:Joi.string().required().min(1),msg:"Has to be non empty."}]}}),window.modalView.modalBindValidation({id:"new-app-license",validateInput:function(){return[{rule:Joi.string().required().regex(/^[a-zA-Z0-9 .,;-]+$/),msg:"Can only contain a to z, A to Z, 0-9, '-', '.', ',' and ';'."}]}}),window.modalView.modalTestAll()},breadcrumb:function(){var e=this;if(window.App.naviView){var t="New";this._upgrade&&(t="Replace ("+window.App.replaceAppData.mount+")"),$("#subNavigationBar .breadcrumb").html('Services: '+t),arangoHelper.buildServicesSubNav("New")}else window.setTimeout(function(){e.breadcrumb()},100)}})}(),function(){"use strict";window.ServiceInstallView=Backbone.View.extend({el:"#content",readOnly:!1,foxxStoreRetry:0,template:templateEngine.createTemplate("serviceInstallView.ejs"),remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},events:{"click #categorySelection":"renderCategories","click #foxxFilters":"resetFilters","keyup #foxxSearch":"search"},initialize:function(e){this.functionsCollection=e.functionsCollection,window.App.replaceApp&&(this._upgrade=!0)},fetchStore:function(){var e=this;this.foxxStoreRetry=1,this.collection.fetch({cache:!1,success:function(){"#services/install"===window.location.hash&&e.render()}})},search:function(){this._installedSubViews[Object.keys(this._installedSubViews)[0]].applyFilter();var t=$("#foxxSearch").val();t?_.each(this._installedSubViews,function(e){e.model.get("name").includes(t)?"true"===$(e.el).attr("shown")&&$(e.el).show():$(e.el).hide()}):this._installedSubViews[Object.keys(this._installedSubViews)[0]].applyFilter()},createSubViews:function(){var i=this;this._installedSubViews={},i.collection.each(function(e){var t=new window.FoxxRepoView({collection:i.functionsCollection,model:e,appsView:i,upgrade:i._upgrade});i._installedSubViews[e.get("name")]=t})},renderCategories:function(e){this._installedSubViews[Object.keys(this._installedSubViews)[0]].renderCategories(e)},resetFilters:function(){$("#foxxSearch").val(""),this._installedSubViews[Object.keys(this._installedSubViews)[0]].resetFilters()},render:function(){if($(this.el).html(this.template.render({services:this.collection})),arangoHelper.buildServicesSubNav("Store"),this.breadcrumb(),0!==this.collection.length||0!==this.foxxStoreRetry)return this.collection.sort(),this.createSubViews(),_.each(this._installedSubViews,function(e){$("#availableFoxxes").append(e.render())}),this;this.fetchStore()},breadcrumb:function(){var e="New";this._upgrade&&(e="Replace ("+window.App.replaceAppData.mount+")"),$("#subNavigationBar .breadcrumb").html('Services: '+e)}})}(),function(){"use strict";window.ServiceInstallUploadView=Backbone.View.extend({el:"#content",readOnly:!1,template:templateEngine.createTemplate("serviceInstallUploadView.ejs"),remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},initialize:function(){window.App.replaceApp&&(this._upgrade=!0)},events:{"click #installUploadService":"installFromUpload"},render:function(){return $(this.el).html(this.template.render({services:this.collection,upgrade:this._upgrade})),this.prepareUpload(),this.breadcrumb(),arangoHelper.createTooltips(".modalTooltips"),this},installFromUpload:function(){arangoHelper.createMountPointModal(this.installFoxxFromZip.bind(this))},testFunction:function(e,t){window.foxxData||(window.foxxData={}),window.foxxData.files=e,window.foxxData.data=t,$("#installUploadService").attr("disabled",!1)},prepareUpload:function(){$("#upload-foxx-zip").uploadFile({url:arangoHelper.databaseUrl("/_api/upload?multipart=true"),allowedTypes:"zip,js",multiple:!1,onSuccess:this.testFunction})},installFoxxFromZip:function(){var e,t,i;void 0===window.foxxData.data?window.foxxData.data=this._uploadData:this._uploadData=window.foxxData.data,window.foxxData.data&&window.modalView.modalTestAll()&&(this._upgrade?e=window.App.replaceAppData.mount:"/"!==(e=window.arangoHelper.escapeHtml($("#new-app-mount").val())).charAt(0)&&(e="/"+e),t={zipFile:window.foxxData.data.filename},(i=arangoHelper.getFoxxFlags()).legacy=Boolean($("#zip-app-islegacy")[0].checked),this.collection.install("zip",t,e,i,this.installCallback.bind(this)));window.modalView.hide()},installCallback:function(e){window.App.navigate("#services",{trigger:!0}),window.App.applicationsView.installCallback(e)},breadcrumb:function(){var e=this;if(window.App.naviView){var t="New";this._upgrade&&(t="Replace ("+window.App.replaceAppData.mount+")"),$("#subNavigationBar .breadcrumb").html('Services: '+t),arangoHelper.buildServicesSubNav("Upload")}else window.setTimeout(function(){e.breadcrumb()},100)}})}(),function(){"use strict";window.ServiceInstallUrlView=Backbone.View.extend({el:"#content",readOnly:!1,template:templateEngine.createTemplate("serviceInstallUrlView.ejs"),remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},initialize:function(){window.App.replaceApp&&(this._upgrade=!0)},events:{"click #installUrlService":"installUrlService"},render:function(){return $(this.el).html(this.template.render({services:this.collection,upgrade:this._upgrade})),this.breadcrumb(),this.setUrlValidators(),arangoHelper.createTooltips(".modalTooltips"),this},breadcrumb:function(){var e=this;if(window.App.naviView){var t="New";this._upgrade&&(t="Replace ("+window.App.replaceAppData.mount+")"),$("#subNavigationBar .breadcrumb").html('Services: '+t),arangoHelper.buildServicesSubNav("Remote")}else window.setTimeout(function(){e.breadcrumb()},100)},installUrlService:function(){arangoHelper.createMountPointModal(this.installFoxxFromUrl.bind(this))},installFoxxFromUrl:function(){var e,t,i;window.modalView.modalTestAll()&&(this._upgrade?e=window.App.replaceAppData.mount:"/"!==(e=window.arangoHelper.escapeHtml($("#new-app-mount").val())).charAt(0)&&(e="/"+e),t={url:window.arangoHelper.escapeHtml($("#repository").val())},i=arangoHelper.getFoxxFlags(),this.collection.install("url",t,e,i,this.installCallback.bind(this)))},setUrlValidators:function(){window.modalView.modalBindValidation({id:"repository",validateInput:function(){return[{rule:Joi.string().required().regex(/^(http)|^(https)/),msg:"No valid http or https url."}]}}),window.modalView.modalTestAll()},installCallback:function(e){window.App.navigate("#services",{trigger:!0}),window.App.applicationsView.installCallback(e)}})}(),function(){"use strict";window.LoggerView=Backbone.View.extend({el:"#content",logsel:"#logEntries",id:"#logContent",initDone:!1,pageSize:20,currentPage:0,logTopics:{},logLevels:[],remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},initialize:function(e){var t=this;e&&(this.options=e),this.collection.setPageSize(this.pageSize),this.initDone||$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/log/level"),contentType:"application/json",processData:!1,success:function(e){t.logTopics=e,_.each(["fatal","error","warning","info","debug"],function(e){t.logLevels.push(e)}),t.initDone=!0}})},currentLoglevel:void 0,defaultLoglevel:"info",events:{"click #logLevelSelection":"renderLogLevel","click #logTopicSelection":"renderLogTopic","click #logFilters":"resetFilters","click #loadMoreEntries":"loadMoreEntries"},template:templateEngine.createTemplate("loggerView.ejs"),templateEntries:templateEngine.createTemplate("loggerViewEntries.ejs"),renderLogTopic:function(e){var i,n=this;this.logTopicOptions||(this.logTopicOptions={}),_.each(this.logTopics,function(e,t){n.logTopicOptions[t]&&(i=n.logTopicOptions[t].active),n.logTopicOptions[t]={name:t,active:i||!1}});var t=$(e.currentTarget).position();t.right="30",this.logTopicView=new window.FilterSelectView({name:"Topic",options:n.logTopicOptions,position:t,callback:n.logTopicCallbackFunction.bind(this),multiple:!0}),this.logTopicView.render()},loadMoreEntries:function(){this.convertModelToJSON()},logTopicCallbackFunction:function(e){this.logTopicOptions=e,this.applyFilter()},logLevelCallbackFunction:function(e){this.logLevelOptions=e,this.applyFilter()},resetFilters:function(){_.each(this.logTopicOptions,function(e){e.active=!1}),_.each(this.logLevelOptions,function(e){e.active=!1}),this.applyFilter()},isFilterActive:function(e){var t=!1;return _.each(e,function(e){e.active&&(t=!0)}),t},changeButton:function(e){e?("level"===e?($("#logLevelSelection").addClass("button-success").removeClass("button-default"),$("#logTopicSelection").addClass("button-default").removeClass("button-success"),$("#filterDesc").html(e)):"topic"===e?($("#logTopicSelection").addClass("button-success").removeClass("button-default"),$("#logLevelSelection").addClass("button-default").removeClass("button-success"),$("#filterDesc").html(e)):"both"===e&&($("#logTopicSelection").addClass("button-success").removeClass("button-default"),$("#logLevelSelection").addClass("button-success").removeClass("button-default"),$("#filterDesc").html("level, topic")),$("#logFilters").show()):($("#logTopicSelection").addClass("button-default").removeClass("button-success"),$("#logLevelSelection").addClass("button-default").removeClass("button-success"),$("#logFilters").hide(),$("#filterDesc").html(""))},applyFilter:function(){var t=this,e=this.isFilterActive(this.logLevelOptions),i=this.isFilterActive(this.logTopicOptions);e&&i?(_.each($("#logEntries").children(),function(e){!1===t.logLevelOptions[$(e).attr("level")].active||!1===t.logTopicOptions[$(e).attr("topic")].active?$(e).hide():t.logLevelOptions[$(e).attr("level")].active&&t.logTopicOptions[$(e).attr("topic")].active&&$(e).show()}),this.changeButton("both")):e&&!i?(_.each($("#logEntries").children(),function(e){!1===t.logLevelOptions[$(e).attr("level")].active?$(e).hide():$(e).show()}),this.changeButton("level")):!e&&i?(_.each($("#logEntries").children(),function(e){!1===t.logTopicOptions[$(e).attr("topic")].active?$(e).hide():$(e).show()}),this.changeButton("topic")):e||i||(_.each($("#logEntries").children(),function(e){$(e).show()}),this.changeButton());var n=0;_.each($("#logEntries").children(),function(e){"flex"===$(e).css("display")&&$(e).css("display","block"),"block"===$(e).css("display")&&n++}),1===n?($(".logBorder").css("visibility","hidden"),$("#noLogEntries").hide()):0===n?$("#noLogEntries").show():($(".logBorder").css("visibility","visible"),$("#noLogEntries").hide())},renderLogLevel:function(e){var i,n=this;this.logLevelOptions||(this.logLevelOptions={}),_.each(this.logLevels,function(e){n.logLevelOptions[e]&&(i=n.logLevelOptions[e].active),n.logLevelOptions[e]={name:e,active:i||!1};var t=arangoHelper.statusColors[e];t&&(n.logLevelOptions[e].color=t)});var t=$(e.currentTarget).position();t.right="115",this.logLevelView=new window.FilterSelectView({name:"Level",options:n.logLevelOptions,position:t,callback:n.logLevelCallbackFunction.bind(this),multiple:!1}),this.logLevelView.render()},setActiveLoglevel:function(e){},initTotalAmount:function(){var e=this;this.collection.fetch({data:$.param({test:!0}),success:function(){e.convertModelToJSON()}}),this.fetchedAmount=!0},invertArray:function(e){var t,i=[],n=0;for(t=e.length-1;0<=t;t--)i[n]=e[t],n++;return i},convertModelToJSON:function(){if(this.fetchedAmount){this.collection.page=this.currentPage,this.currentPage++;var t,i=this,n=[];this.collection.fetch({success:function(e){i.collection.each(function(e){t=new Date(1e3*e.get("timestamp")),n.push({status:e.getLogStatus(),date:arangoHelper.formatDT(t),timestamp:e.get("timestamp"),msg:e.get("text"),topic:e.get("topic")})}),i.renderLogs(i.invertArray(n),e.lastInverseOffset)}})}else this.initTotalAmount()},render:function(){var e=this;return this.currentPage=0,this.initDone?($(this.el).html(this.template.render({})),this.convertModelToJSON()):window.setTimeout(function(){e.render()},100),this},renderLogs:function(e,t){_.each(e,function(e){-1"+t+""):$("#loginDatabase").append("")})}else $("#loginDatabase").hide(),$(".fa-database").hide(),$("#loginDatabase").after('');o.renderDBS()}).error(function(){t?t():location.reload(!0)})}if(frontendConfig.authenticationEnabled&&!0!==e){var i=arangoHelper.getCurrentJwtUsername();if(null!==i&&"undefined"!==i&&void 0!==i){t(arangoHelper.getCurrentJwtUsername(),function(){o.collection.logout(),window.setTimeout(function(){$("#loginUsername").focus()},300)})}else window.setTimeout(function(){$("#loginUsername").focus()},300)}else frontendConfig.authenticationEnabled&&e?t(arangoHelper.getCurrentJwtUsername(),null):t(null,null);return $(".bodyWrapper").show(),o.checkVersion(),this},sortDatabases:function(e){var t;return t=frontendConfig.authenticationEnabled?(t=_.pairs(e),t=_.sortBy(t,function(e){return e[0].toLowerCase()}),_.object(t)):_.sortBy(e,function(e){return e.toLowerCase()})},checkVersion:function(){var t=this;window.setTimeout(function(){var e=document.getElementById("loginSVG").contentDocument;void 0!==frontendConfig.isEnterprise?(frontendConfig.isEnterprise?e.getElementById("logo-enterprise"):e.getElementById("logo-community")).setAttribute("visibility","visible"):t.checkVersion()},150)},clear:function(){$("#loginForm input").removeClass("form-error"),$(".wrong-credentials").hide()},keyPress:function(e){e.ctrlKey&&13===e.keyCode?(e.preventDefault(),this.validate()):e.metaKey&&13===e.keyCode&&(e.preventDefault(),this.validate())},validate:function(e){e.preventDefault(),this.clear();var t=$("#loginUsername").val(),i=$("#loginPassword").val();t&&this.collection.login(t,i,this.loginCallback.bind(this,t,i))},loginCallback:function(e,t,i){var n=this;if(i){if(0===n.loginCounter)return n.loginCounter++,void n.collection.login(e,t,this.loginCallback.bind(this,e));n.loginCounter=0,$(".wrong-credentials").show(),$("#loginDatabase").html(""),$("#loginDatabase").append("")}else n.renderDBSelection(e)},renderDBSelection:function(e){var i=this,t=arangoHelper.databaseUrl("/_api/user/"+encodeURIComponent(e)+"/database","_system");!1===frontendConfig.authenticationEnabled&&(t=arangoHelper.databaseUrl("/_api/database/user")),$(".wrong-credentials").hide(),i.loggedIn=!0,$.ajax(t).success(function(e){if($("#loginForm").hide(),$(".login-window #databases").show(),$("#loginDatabase").html(""),0"+t+""):$("#loginDatabase").append("")})}else $("#loginDatabase").hide(),$(".fa-database").hide(),$("#loginDatabase").after('');i.renderDBS()}).error(function(){$(".wrong-credentials").show()})},renderDBS:function(){var e="Select DB: ";$("#noAccess").hide(),0===$("#loginDatabase").children().length?$("#loginDatabase").is(":visible")?($("#dbForm").remove(),$(".login-window #databases").prepend('
&'"]/)),i.push(window.modalView.createSuccessButton("Yes",e.bind(this,t))),window.modalView.show("modalTable.ejs","Modify Cluster Size",i,n)},initialize:function(){var e=this;clearInterval(this.intervalFunction),window.App.isCluster&&(this.updateServerTime(),this.intervalFunction=window.setInterval(function(){"#nodes"===window.location.hash&&e.render(!1)},this.interval))},deleteNode:function(e){if(!$(e.currentTarget).hasClass("noHover")){var t=this,i=$(e.currentTarget.parentNode.parentNode).attr("node").slice(0,-5);return window.confirm("Do you want to delete this node?")&&$.ajax({type:"POST",url:arangoHelper.databaseUrl("/_admin/cluster/removeServer"),contentType:"application/json",async:!0,data:JSON.stringify(i),success:function(e){t.render(!1)},error:function(){"#nodes"===window.location.hash&&arangoHelper.arangoError("Cluster","Could not fetch cluster information")}}),!1}},navigateToNode:function(e){var t=$(e.currentTarget).attr("node").slice(0,-5);$(e.currentTarget).hasClass("noHover")||window.App.navigate("#node/"+encodeURIComponent(t),{trigger:!0})},render:function(e){if("#nodes"===window.location.hash){var i=this;$("#content").is(":empty")&&arangoHelper.renderEmpty("Please wait. Requesting cluster information...","fa fa-spin fa-circle-o-notch"),!1!==e&&arangoHelper.buildNodesSubNav("Overview");$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/health"),contentType:"application/json",processData:!1,async:!0,success:function(e){"#nodes"===window.location.hash&&function(t){$.ajax({type:"GET",url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",success:function(e){"#nodes"===window.location.hash&&i.continueRender(t,e)}})}(e.Health)},error:function(){"#nodes"===window.location.hash&&arangoHelper.arangoError("Cluster","Could not fetch cluster information")}})}},continueRender:function(e,t){var i=[],n=[],o=!1;_.each(e,function(e,t){e.id=t,"Coordinator"===e.Role?i.push(e):"DBServer"===e.Role&&n.push(e)}),i=_.sortBy(i,function(e){return e.ShortName}),n=_.sortBy(n,function(e){return e.ShortName}),null!==t.numberOfDBServers&&null!==t.numberOfCoordinators&&(o=!0);var a=function(e){this.$el.html(this.template.render({coords:i,dbs:n,scaling:o,scaleProperties:e,plannedDBs:t.numberOfDBServers,plannedCoords:t.numberOfCoordinators})),o||($(".title").css("position","relative"),$(".title").css("top","-4px"),$(".sectionHeader .information").css("margin-top","-3px"))}.bind(this);this.renderCounts(o,a)},updatePlanned:function(e){e.numberOfCoordinators&&($("#plannedCoords").val(e.numberOfCoordinators),this.renderCounts(!0)),e.numberOfDBServers&&($("#plannedDBs").val(e.numberOfDBServers),this.renderCounts(!0))},setCoordSize:function(e){var t=this,i={numberOfCoordinators:e};$.ajax({type:"PUT",url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",data:JSON.stringify(i),success:function(){t.updatePlanned(i)},error:function(){arangoHelper.arangoError("Scale","Could not set coordinator size.")}})},setDBsSize:function(e){var t=this,i={numberOfDBServers:e};$.ajax({type:"PUT",url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",data:JSON.stringify(i),success:function(){t.updatePlanned(i)},error:function(){arangoHelper.arangoError("Scale","Could not set coordinator size.")}})},abortClusterPlanModal:function(){var e=[],t=[];t.push(window.modalView.createReadOnlyEntry("plan-abort-button","Caution","You are aborting the planned cluster plan. All pending servers are going to be removed. Continue?",void 0,void 0,!1,/[<>&'"]/)),e.push(window.modalView.createSuccessButton("Yes",this.abortClusterPlan.bind(this))),window.modalView.show("modalTable.ejs","Modify Cluster Size",e,t)},abortClusterPlan:function(){window.modalView.hide();try{var e=JSON.parse($("#infoCoords > .positive > span").text()),t=JSON.parse($("#infoDBs > .positive > span").text());this.setCoordSize(e),this.setDBsSize(t)}catch(e){arangoHelper.arangoError("Plan","Could not abort Cluster Plan")}},renderCounts:function(a,s){function l(e,t,i,n){var o=''+t+'';i&&!0===a&&(o=o+''+i+''),n&&(o=o+''+n+''),$(e).html(o),a||($(".title").css("position","relative"),$(".title").css("top","-4px"))}var c=this;$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/health"),contentType:"application/json",processData:!1,success:function(e){!function(e){var t=0,i=0,n=0,o=0,a=0,r=0;_.each(e,function(e){"Coordinator"===e.Role?"GOOD"===e.Status?i++:t++:"DBServer"===e.Role&&("GOOD"===e.Status?o++:a++)}),$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",processData:!1,success:function(e){n=Math.abs(i+t-e.numberOfCoordinators),r=Math.abs(o+a-e.numberOfDBServers),s?s({coordsPending:n,coordsOk:i,coordsErrors:t,dbsPending:r,dbsOk:o,dbsErrors:a}):(l("#infoDBs",o,r,a),l("#infoCoords",i,n,t)),c.isPlanFinished()||($(".scaleGroup").addClass("no-hover"),$("#plannedCoords").attr("disabled","disabled"),$("#plannedDBs").attr("disabled","disabled"))}})}(e.Health)}})},isPlanFinished:function(){return!(0<$("#infoDBs").find(".warning").length)&&!(0<$("#infoCoords").find(".warning").length)},addCoord:function(){this.isPlanFinished()?this.changePlanModal(function(){window.modalView.hide(),this.setCoordSize(this.readNumberFromID("#plannedCoords",!0))}.bind(this)):(arangoHelper.arangoNotification("Cluster Plan","Planned state not yet finished."),$(".noty_buttons .button-danger").remove())},removeCoord:function(){this.isPlanFinished()?this.changePlanModal(function(){window.modalView.hide(),this.setCoordSize(this.readNumberFromID("#plannedCoords",!1,!0))}.bind(this)):(arangoHelper.arangoNotification("Cluster Plan","Planned state not yet finished."),$(".noty_buttons .button-danger").remove())},addDBs:function(){this.isPlanFinished()?this.changePlanModal(function(){window.modalView.hide(),this.setDBsSize(this.readNumberFromID("#plannedDBs",!0))}.bind(this)):(arangoHelper.arangoNotification("Cluster Plan","Planned state not yet finished."),$(".noty_buttons .button-danger").remove())},removeDBs:function(){this.isPlanFinished()?this.changePlanModal(function(){window.modalView.hide(),this.setDBsSize(this.readNumberFromID("#plannedDBs",!1,!0))}.bind(this)):(arangoHelper.arangoNotification("Cluster Plan","Planned state not yet finished."),$(".noty_buttons .button-danger").remove())},readNumberFromID:function(e,t,i){var n=$(e).val(),o=!1;try{o=JSON.parse(n)}catch(e){}return t&&o++,i&&1!==o&&o--,o},updateServerTime:function(){this.serverTime=(new Date).getTime()}})}(),function(){"use strict";window.NodeView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("nodeView.ejs"),interval:5e3,dashboards:[],events:{},initialize:function(e){window.App.isCluster&&(this.coordinators=e.coordinators,this.dbServers=e.dbServers,this.coordid=e.coordid,this.updateServerTime())},remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},breadcrumb:function(e){$("#subNavigationBar .breadcrumb").html("Node: "+e)},render:function(){this.$el.html(this.template.render({coords:[]}));var e=function(){this.continueRender(),this.breadcrumb(arangoHelper.getCoordinatorShortName(this.coordid)),$(window).trigger("resize")}.bind(this);this.initCoordDone||this.waitForCoordinators(),this.initDBDone?(this.coordid=window.location.hash.split("/")[1],this.coordinator=this.coordinators.findWhere({id:this.coordid}),e()):this.waitForDBServers(e)},continueRender:function(){var e,t=this;if(this.coordinator)e=this.coordinator.get("name"),this.dashboards[e]&&this.dashboards[e].clearInterval(),this.dashboards[e]=new window.DashboardView({dygraphConfig:window.dygraphConfig,database:window.App.arangoDatabase,serverToShow:{raw:this.coordinator.get("address"),isDBServer:!1,endpoint:this.coordinator.get("protocol")+"://"+this.coordinator.get("address"),target:this.coordinator.get("id")}});else{var i=this.dbServer.toJSON();e=i.name,this.dashboards[e]&&this.dashboards[e].clearInterval(),this.dashboards[e]=new window.DashboardView({dygraphConfig:null,database:window.App.arangoDatabase,serverToShow:{raw:i.address,isDBServer:!0,endpoint:i.endpoint,id:i.id,name:i.name,status:i.status,target:i.id}})}this.dashboards[e].render(),window.setTimeout(function(){t.dashboards[e].resize()},500)},waitForCoordinators:function(e){var t=this;window.setTimeout(function(){0===t.coordinators.length?t.waitForCoordinators(e):(t.coordinator=t.coordinators.findWhere({id:t.coordid}),t.initCoordDone=!0,e&&e())},200)},waitForDBServers:function(e){var i=this;window.setTimeout(function(){0===i.dbServers[0].length?i.waitForDBServers(e):(i.initDBDone=!0,i.dbServer=i.dbServers[0],i.dbServer.each(function(e){var t=e.get("id");t===window.location.hash.split("/")[1]&&(i.dbServer=i.dbServer.findWhere({id:t}))}),e())},200)},updateServerTime:function(){this.serverTime=(new Date).getTime()}})}(),function(){"use strict";window.NotificationView=Backbone.View.extend({events:{"click .navlogo #stat_hd":"toggleNotification","click .notificationItem .fa":"removeNotification","click #removeAllNotifications":"removeAllNotifications"},initialize:function(){this.collection.bind("add",this.renderNotifications.bind(this)),this.collection.bind("remove",this.renderNotifications.bind(this)),this.collection.bind("reset",this.renderNotifications.bind(this)),window.setTimeout(function(){!1===frontendConfig.authenticationEnabled&&!1===frontendConfig.isCluster&&!0===arangoHelper.showAuthDialog()&&window.arangoHelper.arangoWarning("Warning","Authentication is disabled. Do not use this setup in production mode.")},2e3)},notificationItem:templateEngine.createTemplate("notificationItem.ejs"),el:"#notificationBar",template:templateEngine.createTemplate("notificationView.ejs"),toggleNotification:function(){0!==this.collection.length&&$("#notification_menu").toggle()},removeAllNotifications:function(){$.noty.clearQueue(),$.noty.closeAll(),this.collection.reset(),$("#notification_menu").hide()},removeNotification:function(e){var t=e.target.id;this.collection.get(t).destroy()},renderNotifications:function(e,t,i){if(i&&i.add){var n,o=this.collection.at(this.collection.length-1),a=o.get("title"),r=5e3,s=["click"];if(o.get("content")&&(a=a+": "+o.get("content")),"error"===o.get("type")?(r=!1,s=["button"],n=[{addClass:"button-danger",text:"Close",onClick:function(e){e.close()}}]):"warning"===o.get("type")&&(r=15e3,n=[{addClass:"button-warning",text:"Close",onClick:function(e){e.close()}},{addClass:"button-danger",text:"Don't show again.",onClick:function(e){e.close(),window.arangoHelper.doNotShowAgain()}}]),$.noty.clearQueue(),$.noty.closeAll(),noty({theme:"relax",text:a,template:'
This will generate a package containing a lot of commonly required information about your query and environment that helps the ArangoDB Team to reproduce your issue. This debug package will include:
collection names
collection indexes
attribute names
bind parameters
Additionally, samples of your data will be included with all string values obfuscated in a non-reversible way if below checkbox is ticked.
If disabled, this package will not include any data.
Please open the package locally and check if it contains anything that you are not allowed/willing to share and obfuscate it before uploading. Including this package in bug reports will lower the amount of questioning back and forth to reproduce the issue on our side and is much appreciated.
",void 0,!1,!1)),t.push(window.modalView.createCheckboxEntry("debug-download-package-examples","Include obfuscated examples","includeExamples","Includes an example set of documents, obfuscating all string values inside the data. This helps the ArangoDB Team as many issues are related to the document structure / format and the indexes defined on them.",!0)),e.push(window.modalView.createSuccessButton("Download Package",this.downloadDebugZip.bind(this))),window.modalView.show("modalTable.ejs","Download Query Debug Package",e,t,void 0,void 0)},downloadDebugZip:function(){if(!this.verifyQueryAndParams()){var e=this.aqlEditor.getValue();if(""!==e&&null!=e){var t={query:e,bindVars:this.bindParamTableObj||{},examples:$("#debug-download-package-examples").is(":checked")};arangoHelper.downloadPost("query/debugDump",JSON.stringify(t),function(){window.modalView.hide()},function(e,t){window.arangoHelper.arangoError("Debug Dump",e+": "+t),window.modalView.hide()})}else arangoHelper.arangoError("Query error","Could not create a debug package.")}},fillExplain:function(t,i,n){var e,o=this;if("false"!==(e=n?this.readQueryData(null,null,!0):this.readQueryData())&&($("#outputEditorWrapper"+i+" .queryExecutionTime").text(""),this.execPending=!1,e)){var a,r=function(){$("#outputEditorWrapper"+i+" #spinner").remove(),$("#outputEditor"+i).css("opacity","1"),$("#outputEditorWrapper"+i+" .fa-close").show(),$("#outputEditorWrapper"+i+" .switchAce").show()};a=n?arangoHelper.databaseUrl("/_admin/aardvark/query/profile"):arangoHelper.databaseUrl("/_admin/aardvark/query/explain"),$.ajax({type:"POST",url:a,data:e,contentType:"application/json",processData:!1,success:function(e){e.msg&&e.msg.errorMessage?(o.removeOutputEditor(i),n?arangoHelper.arangoError("Profile",e.msg):arangoHelper.arangoError("Explain",e.msg)):(o.cachedQueries[i]=e,t.setValue(e.msg,1),o.deselect(t),$.noty.clearQueue(),$.noty.closeAll(),o.handleResult(i),$(".centralRow").animate({scrollTop:$("#queryContent").height()},"fast")),r()},error:function(e){try{var t=JSON.parse(e.responseText);n?arangoHelper.arangoError("Profile",t.errorMessage):arangoHelper.arangoError("Explain",t.errorMessage)}catch(e){n?arangoHelper.arangoError("Profile","ERROR"):arangoHelper.arangoError("Explain","ERROR")}o.handleResult(i),o.removeOutputEditor(i),r()}})}},removeOutputEditor:function(e){$("#outputEditorWrapper"+e).hide(),$("#outputEditorWrapper"+e).remove(),0===$(".outputEditorWrapper").length&&$("#removeResults").hide()},getCachedQueryAfterRender:function(){if(!1===this.renderComplete&&this.aqlEditor){var e=this.getCachedQuery(),t=this;if(null!=e&&""!==e&&0"+_.escape(e)+" results")})},render:function(){this.refreshAQL(),this.renderComplete=!1,this.$el.html(this.template.render({})),this.afterRender(),this.initDone||(this.settings.aqlWidth=$(".aqlEditorWrapper").width()),"json"===this.bindParamMode&&this.toggleBindParams(),this.initDone=!0,this.renderBindParamTable(!0),this.restoreCachedQueries(),this.delegateEvents(),this.restoreQuerySize(),this.getCachedQueryAfterRender()},cleanupGraphs:function(){void 0===this.graphViewers&&null===this.graphViewers||(_.each(this.graphViewers,function(e){void 0!==e&&(e.killCurrentGraph(),e.remove())}),$("canvas").remove(),this.graphViewers=null,this.graphViewers=[])},afterRender:function(){var e=this;this.initAce(),this.initTables(),this.fillSelectBoxes(),this.makeResizeable(),this.initQueryImport(),$(".inputEditorWrapper").height($(window).height()/10*5+25),window.setTimeout(function(){e.resize()},10),e.deselect(e.aqlEditor)},restoreCachedQueries:function(){var i=this;0
",$("#replication-info").append(o)}},goToApplier:function(e){var t=btoa($(e.currentTarget).attr("data"));window.App.navigate("#replication/applier/"+t+"/"+btoa("_system"),{trigger:!0})},goToApplierFromTable:function(e){var t=btoa(window.location.origin),i=btoa($(e.currentTarget).find("#applier-database-id").html()),n=$(e.currentTarget).find("#applier-running-id").html();"true"===n||!0===n?window.App.navigate("#replication/applier/"+t+"/"+i,{trigger:!0}):arangoHelper.arangoMessage("Replication","This applier is not running.")},getActiveFailoverEndpoints:function(){var t=this;$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/cluster/endpoints"),contentType:"application/json",success:function(e){e.endpoints?t.renderEndpoints(e.endpoints):t.renderEndpoints()},error:function(){t.renderEndpoints()}})},renderEndpoints:function(e){var t=this;if(e){var i=e[0],n=e.slice(1,e.length);$("#nodes-leader-id").html(i.endpoint),$("#nodes-followers-id").html(""),_.each(n,function(e){$("#nodes-followers-id").append(''+e.endpoint+"")})}else $("#nodes-leader-id").html("Error"),$("#nodes-followers-id").html("Error")},parseEndpoint:function(e,t){var i;return"[::1]"===e.slice(6,11)?i=window.location.host.split(":")[0]+":"+e.split(":")[4]:"tcp://"===e.slice(0,6)?i="http://"+e.slice(6,e.length):"ssl://"===e.slice(0,6)&&(i="https://"+e.slice(6,e.length)),t&&(i=window.location.protocol+"//"+i),i||e},getLoggerState:function(){var t=this;$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/replication/logger-state"),contentType:"application/json",success:function(e){"#replication"===window.location.hash?(t.updateLoggerGraphsData(e),t.nvchartsInit?t.rerenderLoggerGraphs():t.initLoggerGraphs(),t.renderLoggerState(e.server,e.clients,e.state)):t.updateLoggerGraphsData(e)},error:function(){arangoHelper.arangoError("Replication","Could not fetch the leaders logger state.")}})},getApplierStates:function(t){var e,i=this;e=t?arangoHelper.databaseUrl("/_api/replication/applier-state?global=true"):arangoHelper.databaseUrl("/_api/replication/applier-state-all"),$.ajax({type:"GET",cache:!1,url:e,contentType:"application/json",success:function(e){t?i.renderApplierState(e,!0):i.renderApplierState(e)},error:function(){t?arangoHelper.arangoError("Replication","Could not fetch the followers global applier state."):arangoHelper.arangoError("Replication","Could not fetch the followers applier state.")}})},renderApplierState:function(i,e){var o,a=this;e&&(i.database="All databases",i={"All databases":i});var r,s=0,n=[],l=[];_.each(i,function(e,t){e.state.running?n.push(i[t]):(i[t].database=t,l.push(i[t]))}),n=_.sortBy(n,"database"),l=_.sortBy(l,"database"),i=n.concat(l),$("#repl-follower-table tbody").html(""),_.each(i,function(e,t){var i;o="undefined"!==e.endpoint&&e.endpoint?a.parseEndpoint(e.endpoint):"not available","inactive"!==e.state.phase&&!0!==e.state.running&&s++;var n="active";"inactive"===e.state.phase&&(n="inactive"),0===e.state.lastError.errorNum?i="inactive"!==e.state.phase||e.state.running?'':"n/a":(i='',s++),$("#repl-follower-table tbody").append('
'+e.database+'
'+e.state.running+"
"+e.state.phase+'
'+o+"
"+e.state.lastAppliedContinuousTick+"
"+i+"
"),r=e.server.serverId}),$("#logger-lastLogTick-id").html(r),0===s?this.renderHealth(!1):this.renderHealth(!0,"Some appliers are not running or do have errors.")},renderHealth:function(e,t){e?($("#info-msg-id").addClass("negative"),$("#info-msg-id").removeClass("positive"),$("#info-msg-id").html('Bad '),t&&($("#info-msg-id").attr("title",t),$("#info-msg-id").addClass("modalTooltips"),arangoHelper.createTooltips(".modalTooltips"))):($("#info-msg-id").addClass("positive"),$("#info-msg-id").removeClass("negative"),$("#info-msg-id").removeClass("modalTooltips"),$("#info-msg-id").html('Good '))},getStateData:function(e){3===this.mode?(this.getActiveFailoverEndpoints(),this.getLoggerState()):2===this.mode?"leader"===this.info.role?this.getLoggerState():this.getApplierStates(!0):1===this.mode&&("leader"===this.info.role?this.getLoggerState():this.getApplierStates()),e&&e()},updateLoggerGraphsData:function(e){this.loggerGraphsData.length>this.keepEntries&&this.loggerGraphsData.pop(),this.loggerGraphsData.push(e)},parseLoggerData:function(){var e,o=this,t=this.loggerGraphsData;this.colors||(this.colors=randomColor({hue:"blue",count:this.loggerGraphsData.length}));var a={leader:{key:e=3===o.mode?"Leader":"Master",values:[],strokeWidth:2,color:"#2ecc71"}},r={leader:{key:e,values:[],strokeWidth:2,color:"#2ecc71"}};return _.each(t,function(i){a.leader.values.push({x:Date.parse(i.state.time),y:0}),r.leader.values.push({x:Date.parse(i.state.time),y:0});var n=0;_.each(i.clients,function(e){var t;a[e.serverId]||(t=3===o.mode?"Follower ("+e.serverId+")":"Slave ("+e.serverId+")",a[e.serverId]={key:t,color:o.colors[n],strokeWidth:1,values:[]},r[e.serverId]={key:t,color:o.colors[n],strokeWidth:1,values:[]},n++);a[e.serverId].values.push({x:Date.parse(e.time),y:(Date.parse(i.state.time)-Date.parse(e.time))/1e3*-1}),r[e.serverId].values.push({x:Date.parse(e.time),y:-1*(i.state.lastLogTick-e.lastServedTick)})})}),{graphDataTick:_.toArray(r),graphDataTime:_.toArray(a)}},initLoggerGraphs:function(){var t=this;nv.addGraph(function(){t.charts.replicationTimeChart=nv.models.lineChart().options({duration:300,useInteractiveGuideline:!0,forceY:[2,-10]}),t.charts.replicationTimeChart.xAxis.axisLabel("").tickFormat(function(e){var t=new Date(e);return(t.getHours()<10?"0":"")+t.getHours()+":"+(t.getMinutes()<10?"0":"")+t.getMinutes()+":"+(t.getSeconds()<10?"0":"")+t.getSeconds()}).staggerLabels(!1),t.charts.replicationTimeChart.yAxis.axisLabel("Last call ago (in s)").tickFormat(function(e){return null===e?"N/A":d3.format(",.0f")(e)});var e=t.parseLoggerData().graphDataTime;return d3.select("#replicationTimeChart svg").datum(e).call(t.charts.replicationTimeChart),nv.utils.windowResize(t.charts.replicationTimeChart.update),t.charts.replicationTimeChart}),nv.addGraph(function(){t.charts.replicationTickChart=nv.models.lineChart().options({duration:300,useInteractiveGuideline:!0,forceY:[2,void 0]}),t.charts.replicationTickChart.xAxis.axisLabel("").tickFormat(function(e){var t=new Date(e);return(t.getHours()<10?"0":"")+t.getHours()+":"+(t.getMinutes()<10?"0":"")+t.getMinutes()+":"+(t.getSeconds()<10?"0":"")+t.getSeconds()}).staggerLabels(!1),t.charts.replicationTickChart.yAxis.axisLabel("Ticks behind").tickFormat(function(e){return null===e?"N/A":d3.format(",.0f")(e)});var e=t.parseLoggerData().graphDataTick;return d3.select("#replicationTickChart svg").datum(e).call(t.charts.replicationTickChart),nv.utils.windowResize(t.charts.replicationTickChart.update),t.charts.replicationTickChart}),t.nvchartsInit=!0},rerenderLoggerGraphs:function(){d3.select("#replicationTimeChart svg").datum(this.parseLoggerData().graphDataTime).transition().duration(500).call(this.charts.replicationTimeChart),d3.select("#replicationTickChart svg").datum(this.parseLoggerData().graphDataTick).transition().duration(500).call(this.charts.replicationTickChart),_.each(this.charts,function(e){nv.utils.windowResize(e.update)})},renderLoggerState:function(e,t,i){e&&t&&i?($("#logger-running-id").html(i.running),$("#logger-version-id").html(e.version),$("#logger-serverid-id").html(e.serverId),$("#logger-time-id").html(i.time),$("#logger-lastLogTick-id").html(i.lastLogTick),$("#logger-totalEvents-id").html(i.totalEvents),$("#repl-logger-clients tbody").html(""),_.each(t,function(e){$("#repl-logger-clients tbody").append("
"+e.syncerId+"
"+e.serverId+"
"+e.clientInfo+"
"+e.time+"
"+e.lastServedTick+"
")}),i.running?this.renderHealth(!1):this.renderHealth(!0,"The logger thread is not running")):($("#logger-running-id").html("Error"),$("#logger-endpoint-id").html("Error"),$("#logger-version-id").html("Error"),$("#logger-serverid-id").html("Error"),$("#logger-time-id").html("Error"),this.renderHealth(!0,"Unexpected data from the logger thread."))},getMode:function(t){var i=this;$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/aardvark/replication/mode"),contentType:"application/json",success:function(e){!e.mode&&0!==e.mode||(Number.isInteger(e.mode)?(i.mode=e.mode,0!==e.mode?i.info.state="enabled":i.info.state="disabled"):i.mode="undefined",e.role&&(i.info.role=e.role),3===i.mode?(i.info.mode="Active Failover",i.info.level="Server"):2===i.mode?(i.info.mode="Master/Slave",i.info.level="Server"):1===i.mode&&(i.info.mode="Master/Slave","follower"===i.info.role?i.info.level="Database":i.info.level="Check slaves for details")),t&&t()},error:function(){arangoHelper.arangoError("Replication","Could not fetch the replication state.")}})}})}(),function(){"use strict";window.ScaleView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("scaleView.ejs"),interval:1e4,knownServers:[],events:{"click #addCoord":"addCoord","click #removeCoord":"removeCoord","click #addDBs":"addDBs","click #removeDBs":"removeDBs"},setCoordSize:function(e){var t=this,i={numberOfCoordinators:e};$.ajax({type:"PUT",url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",data:JSON.stringify(i),success:function(){t.updateTable(i)},error:function(){arangoHelper.arangoError("Scale","Could not set coordinator size.")}})},setDBsSize:function(e){var t=this,i={numberOfDBServers:e};$.ajax({type:"PUT",url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",data:JSON.stringify(i),success:function(){t.updateTable(i)},error:function(){arangoHelper.arangoError("Scale","Could not set coordinator size.")}})},addCoord:function(){this.setCoordSize(this.readNumberFromID("#plannedCoords",!0))},removeCoord:function(){this.setCoordSize(this.readNumberFromID("#plannedCoords",!1,!0))},addDBs:function(){this.setDBsSize(this.readNumberFromID("#plannedDBs",!0))},removeDBs:function(){this.setDBsSize(this.readNumberFromID("#plannedDBs",!1,!0))},readNumberFromID:function(e,t,i){var n=$(e).html(),o=!1;try{o=JSON.parse(n)}catch(e){}return t&&o++,i&&1!==o&&o--,o},initialize:function(e){var t=this;clearInterval(this.intervalFunction),window.App.isCluster&&"_system"===frontendConfig.db&&(this.dbServers=e.dbServers,this.coordinators=e.coordinators,this.updateServerTime(),this.intervalFunction=window.setInterval(function(){"#sNodes"===window.location.hash&&t.coordinators.fetch({success:function(){t.dbServers.fetch({success:function(){t.continueRender(!0)}})}})},this.interval))},render:function(){var e=this,t=function(){this.waitForDBServers(function(){e.continueRender()})}.bind(this);this.initDoneCoords?t():this.waitForCoordinators(t),window.arangoHelper.buildNodesSubNav("scale")},continueRender:function(e){var t,i,n=this;t=this.coordinators.toJSON(),i=this.dbServers.toJSON(),this.$el.html(this.template.render({runningCoords:t.length,runningDBs:i.length,plannedCoords:void 0,plannedDBs:void 0,initialized:e})),$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",processData:!1,success:function(e){n.updateTable(e)}})},updateTable:function(e){var t='scaling in progress ',i='no scaling process active';e.numberOfCoordinators&&($("#plannedCoords").html(e.numberOfCoordinators),this.coordinators.toJSON().length===e.numberOfCoordinators?$("#statusCoords").html(i):$("#statusCoords").html(t)),e.numberOfDBServers&&($("#plannedDBs").html(e.numberOfDBServers),this.dbServers.toJSON().length===e.numberOfDBServers?$("#statusDBs").html(i):$("#statusDBs").html(t))},waitForDBServers:function(e){var t=this;0===this.dbServers.length?window.setInterval(function(){t.waitForDBServers(e)},300):e()},waitForCoordinators:function(e){var t=this;window.setTimeout(function(){0===t.coordinators.length?t.waitForCoordinators(e):(t.initDoneCoords=!0,e())},200)},updateServerTime:function(){this.serverTime=(new Date).getTime()}})}(),function(){"use strict";window.SettingsView=Backbone.View.extend({el:"#content",readOnly:!1,initialize:function(e){this.collectionName=e.collectionName,this.model=this.collection},events:{},render:function(){this.breadcrumb(),arangoHelper.buildCollectionSubNav(this.collectionName,"Settings"),this.renderSettings()},breadcrumb:function(){$("#subNavigationBar .breadcrumb").html("Collection: "+this.collectionName)},unloadCollection:function(){if(!this.readOnly){var e=function(e){e?arangoHelper.arangoError("Collection error",this.model.get("name")+" could not be unloaded."):void 0===e?(this.model.set("status","unloading"),this.render()):"#collections"===window.location.hash?(this.model.set("status","unloaded"),this.render()):arangoHelper.arangoNotification("Collection "+this.model.get("name")+" unloaded.")}.bind(this);this.model.unloadCollection(e),window.modalView.hide()}},loadCollection:function(){if(!this.readOnly){var e=function(e){e?arangoHelper.arangoError("Collection error",this.model.get("name")+" could not be loaded."):void 0===e?(this.model.set("status","loading"),this.render()):"#collections"===window.location.hash?(this.model.set("status","loaded"),this.render()):arangoHelper.arangoNotification("Collection "+this.model.get("name")+" loaded.")}.bind(this);this.model.loadCollection(e),window.modalView.hide()}},truncateCollection:function(){this.readOnly||(this.model.truncateCollection(),$(".modal-delete-confirmation").hide(),window.modalView.hide())},warmupCollection:function(){this.readOnly||(this.model.warmupCollection(),$(".modal-delete-confirmation").hide(),window.modalView.hide())},deleteCollection:function(){this.readOnly||this.model.destroy({error:function(e,t){arangoHelper.arangoError("Could not drop collection: "+t.responseJSON.errorMessage)},success:function(){window.App.navigate("#collections",{trigger:!0})}})},saveModifiedCollection:function(){if(!this.readOnly){var e=function(e,t){if(e)arangoHelper.arangoError("Error","Could not get coordinator info");else{var i;i=t?this.model.get("name"):$("#change-collection-name").val();var n=this.model.get("status");if("loaded"===n){var a,r;if("rocksdb"!==frontendConfig.engine)try{a=JSON.parse(1024*$("#change-collection-size").val()*1024)}catch(e){return arangoHelper.arangoError("Please enter a valid journal size number."),0}if("rocksdb"!==frontendConfig.engine)try{if((r=JSON.parse($("#change-index-buckets").val()))<1||parseInt(r,10)!==Math.pow(2,Math.log2(r)))throw new Error("invalid indexBuckets value")}catch(e){return arangoHelper.arangoError("Please enter a valid number of index buckets."),0}var o=this,s=function(e,t){e?(o.render(),arangoHelper.arangoError("Collection error: "+t.responseJSON.errorMessage)):(arangoHelper.arangoNotification("Collection: Successfully changed."),window.App.navigate("#cSettings/"+i,{trigger:!0}))},l=function(e){var t=!1;if(e)arangoHelper.arangoError("Collection error: "+e.responseText);else{var i,n,o=$("#change-collection-sync").val();if(frontendConfig.isCluster){i=$("#change-replication-factor").val(),n=$("#change-min-replication-factor").val();try{Number.parseInt(n)>Number.parseInt(i)&&(arangoHelper.arangoError("Change Collection","Minimal replication factor is not allowed to be greater then replication factor"),t=!0)}catch(e){}}t||this.model.changeCollection(o,a,r,i,n,s)}}.bind(this);!1===frontendConfig.isCluster?this.model.renameCollection(i,l):l()}else if("unloaded"===n)if(this.model.get("name")!==i){var c=function(e,t){e?arangoHelper.arangoError("Collection"+t.responseText):(arangoHelper.arangoNotification("CollectionSuccessfully changed."),window.App.navigate("#cSettings/"+i,{trigger:!0}))};!1===frontendConfig.isCluster?this.model.renameCollection(i,c):c()}else window.modalView.hide()}}.bind(this);window.isCoordinator(e)}},changeViewToReadOnly:function(){window.App.settingsView.readOnly=!0,$(".breadcrumb").html($(".breadcrumb").html()+" (read-only)"),$(".modal-body input").prop("disabled","true"),$(".modal-body select").prop("disabled","true"),$(".modal-footer button").addClass("disabled"),$(".modal-footer button").unbind("click")},renderSettings:function(){var s=this,e=function(e,t){if(e)arangoHelper.arangoError("Error","Could not get coordinator info");else{var i=!1;"loaded"===this.model.get("status")&&(i=!0);var n=[],a=[];t||("_"===this.model.get("name").substr(0,1)?a.push(window.modalView.createReadOnlyEntry("change-collection-name","Name",this.model.get("name"),!1,"",!0,[{rule:Joi.string().regex(/^[a-zA-Z]/),msg:"Collection name must always start with a letter."},{rule:Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),msg:'Only Symbols "_" and "-" are allowed.'},{rule:Joi.string().required(),msg:"No collection name given."}])):a.push(window.modalView.createTextEntry("change-collection-name","Name",this.model.get("name"),!1,"",!0,[{rule:Joi.string().regex(/^[a-zA-Z]/),msg:"Collection name must always start with a letter."},{rule:Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),msg:'Only Symbols "_" and "-" are allowed.'},{rule:Joi.string().required(),msg:"No collection name given."}])));var r=function(){a.push(window.modalView.createReadOnlyEntry("change-collection-id","ID",this.model.get("id"),"")),a.push(window.modalView.createReadOnlyEntry("change-collection-type","Type",this.model.get("type"),"")),a.push(window.modalView.createReadOnlyEntry("change-collection-status","Status",this.model.get("status"),"")),n.push(window.modalView.createDeleteButton("Delete",this.deleteCollection.bind(this))),n.push(window.modalView.createDeleteButton("Truncate",this.truncateCollection.bind(this))),"rocksdb"===frontendConfig.engine&&n.push(window.modalView.createNotificationButton("Load Indexes into Memory",this.warmupCollection.bind(this))),i?n.push(window.modalView.createNotificationButton("Unload",this.unloadCollection.bind(this))):n.push(window.modalView.createNotificationButton("Load",this.loadCollection.bind(this))),n.push(window.modalView.createSuccessButton("Save",this.saveModifiedCollection.bind(this)));window.modalView.show(["modalTable.ejs","indicesView.ejs"],"Modify Collection",n,a,null,null,this.events,null,["General","Indexes"],"content"),$($("#infoTab").children()[1]).remove()}.bind(this);if(i){this.model.getProperties(function(e,t){if(e)arangoHelper.arangoError("Collection","Could not fetch properties");else{var i=t.waitForSync;if(t.journalSize){var n=t.journalSize/1048576,o=t.indexBuckets;a.push(window.modalView.createTextEntry("change-collection-size","Journal size",n,"The maximal size of a journal or datafile (in MB). Must be at least 1.","",!0,[{rule:Joi.string().allow("").optional().regex(/^[0-9]*$/),msg:"Must be a number."}]))}o&&a.push(window.modalView.createTextEntry("change-index-buckets","Index buckets",o,"The number of index buckets for this collection. Must be at least 1 and a power of 2.","",!0,[{rule:Joi.string().allow("").optional().regex(/^[1-9][0-9]*$/),msg:"Must be a number greater than 1 and a power of 2."}])),t.replicationFactor&&frontendConfig.isCluster&&("satellite"===t.replicationFactor?(a.push(window.modalView.createReadOnlyEntry("change-replication-factor","Replication factor",t.replicationFactor,"This collection is a satellite collection. The replicationFactor is not changeable.","",!0)),a.push(window.modalView.createReadOnlyEntry("change-min-replication-factor","Minimal replication factor",t.minReplicationFactor,"This collection is a satellite collection. The minReplicationFactor is not changeable.","",!0))):(a.push(window.modalView.createTextEntry("change-replication-factor","Replication factor",t.replicationFactor,"The replicationFactor parameter is the total number of copies being kept, that is, it is one plus the number of followers. Must be a number.","",!0,[{rule:Joi.string().allow("").optional().regex(/^[0-9]*$/),msg:"Must be a number."}])),a.push(window.modalView.createTextEntry("change-min-replication-factor","Minimal Replication factor",t.minReplicationFactor,"Numeric value. Must be at least 1. Must be smaller or equal compared to the replicationFactor. Total number of copies of the data in the cluster. If we get below this value the collection will be read-only until enough copies are created.","",!0,[{rule:Joi.string().allow("").optional().regex(/^[1-9]*$/),msg:"Must be a number. Must be at least 1 and has to be smaller or equal compared to the replicationFactor."}])))),a.push(window.modalView.createSelectEntry("change-collection-sync","Wait for sync",i,"Synchronize to disk before returning from a create or update of a document.",[{value:!1,label:"No"},{value:!0,label:"Yes"}]))}r(),arangoHelper.checkCollectionPermissions(s.collectionName,s.changeViewToReadOnly.bind(this))})}else r(),arangoHelper.checkCollectionPermissions(s.collectionName,s.changeViewToReadOnly.bind(this))}}.bind(this);window.isCoordinator(e)}})}(),function(){"use strict";window.ShardsView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("shardsView.ejs"),interval:1e4,knownServers:[],pending:!1,visibleCollection:null,events:{"click #shardsContent .shardLeader span":"moveShard","click #shardsContent .shardFollowers span":"moveShardFollowers","click #rebalanceShards":"rebalanceShards","click .sectionHeader":"toggleSections"},initialize:function(e){var t=this;t.dbServers=e.dbServers,clearInterval(this.intervalFunction),window.App.isCluster&&(this.updateServerTime(),this.intervalFunction=window.setInterval(function(){"#shards"===window.location.hash&&t.render(!1)},this.interval))},remove:function(){return clearInterval(this.intervalFunction),this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},renderArrows:function(e){$("#shardsContent .fa-arrow-down").removeClass("fa-arrow-down").addClass("fa-arrow-right"),$(e.currentTarget).find(".fa-arrow-right").removeClass("fa-arrow-right").addClass("fa-arrow-down")},toggleSections:function(e){var t=$(e.currentTarget).parent().attr("id");this.visibleCollection=t,$(".sectionShardContent").hide(),$(e.currentTarget).next().show(),this.renderArrows(e),this.getShardDetails(t)},renderShardDetail:function(i,e){var n=0,o=0,a=0;_.each(e.results[i].Plan,function(e,t){if(e.progress)if(0===e.progress.current){$("#"+i+"-"+t+" .shardProgress").html("n/A")}else n=(e.progress.current/e.progress.total*100).toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]+"%",$("#"+i+"-"+t+" .shardProgress").html(n);else $("#"+i+"-"+t+" .shardProgress").html(''),o++;a++}),a===o?($("#"+i+" .shardSyncIcons i").addClass("fa-check-circle").removeClass(".fa-times-circle"),$("#"+i+" .notInSync").addClass("inSync").removeClass("notInSync")):$("#"+i+" .shardSyncIcons i").addClass("fa-times-circle").removeClass("fa-check-circle")},checkActiveShardDisplay:function(){var t=this;_.each($(".sectionShard"),function(e){$(e).find(".sectionShardContent").is(":visible")&&t.getShardDetails($(e).attr("id"))})},getShardDetails:function(t){var i=this,e={collection:t};$("#"+t+" .shardProgress").html(''),$.ajax({type:"PUT",cache:!1,data:JSON.stringify(e),url:arangoHelper.databaseUrl("/_admin/cluster/collectionShardDistribution"),contentType:"application/json",processData:!1,async:!0,success:function(e){i.renderShardDetail(t,e)},error:function(e){}})},render:function(e){if("#shards"===window.location.hash&&!1===this.pending){var t=this;t.pending=!0,$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/shardDistribution"),contentType:"application/json",processData:!1,async:!0,success:function(e){var i=t.pending=!1;t.shardDistribution=e.results,_.each(e.results,function(e,t){"error"!==t&&"code"!==t&&("_"!==t.substring(0,1)&&(i=!0),(t.startsWith("_local_")||t.startsWith("_to_")||t.startsWith("_from_"))&&(i=!0))}),i?t.continueRender(e.results):arangoHelper.renderEmpty("No collections and no shards available"),t.checkActiveShardDisplay()},error:function(e){0!==e.readyState&&arangoHelper.arangoError("Cluster","Could not fetch sharding information.")}}),!1!==e&&arangoHelper.buildNodesSubNav("Shards")}},moveShardFollowers:function(e){var t=$(e.currentTarget).html();this.moveShard(e,t)},moveShard:function(e,t){var i,n,o,a,r=this,s=window.App.currentDB.get("name");n=$(e.currentTarget).parent().parent().attr("collection"),o=$(e.currentTarget).parent().parent().attr("shard"),i=t?(a=$(e.currentTarget).parent().parent().attr("leader"),a=arangoHelper.getDatabaseServerId(a),arangoHelper.getDatabaseServerId(t)):(i=$(e.currentTarget).parent().parent().attr("leader"),arangoHelper.getDatabaseServerId(i));var l=[],c=[],d={},u=[];r.dbServers[0].fetch({success:function(){r.dbServers[0].each(function(e){e.get("id")!==i&&(d[e.get("name")]={value:e.get("id"),label:e.get("name")})}),_.each(r.shardDistribution[n].Plan[o].followers,function(e){delete d[e]}),t&&delete d[arangoHelper.getDatabaseShortName(a)],_.each(d,function(e){u.push(e)}),0!==(u=u.reverse()).length?(c.push(window.modalView.createSelectEntry("toDBServer","Destination",void 0,"Please select the target database server. The selected database server will be the new leader of the shard.",u)),l.push(window.modalView.createSuccessButton("Move",r.confirmMoveShards.bind(this,s,n,o,i))),window.modalView.show("modalTable.ejs","Move shard: "+o,l,c)):arangoHelper.arangoMessage("Shards","No database server for moving the shard is available.")}})},confirmMoveShards:function(e,t,i,n){var o=$("#toDBServer").val(),a={database:e,collection:t,shard:i,fromServer:n,toServer:o};$.ajax({type:"POST",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/moveShard"),contentType:"application/json",processData:!1,data:JSON.stringify(a),async:!0,success:function(e){e.id&&(arangoHelper.arangoNotification("Shard "+i+" will be moved to "+arangoHelper.getDatabaseShortName(o)+"."),window.setTimeout(function(){window.App.shardsView.render()},3e3))},error:function(){arangoHelper.arangoError("Shard "+i+" could not be moved to "+arangoHelper.getDatabaseShortName(o)+".")}}),window.modalView.hide()},rebalanceShards:function(){var t=this;$.ajax({type:"POST",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/rebalanceShards"),contentType:"application/json",processData:!1,data:JSON.stringify({}),async:!0,success:function(e){!0===e&&(window.setTimeout(function(){t.render(!1)},3e3),arangoHelper.arangoNotification("Started rebalance process."))},error:function(){arangoHelper.arangoError("Could not start rebalance process.")}}),window.modalView.hide()},continueRender:function(r){delete r.code,delete r.error,_.each(r,function(e,t){var i={Plan:{},Current:{}};if(t.startsWith("_local_")){var n=t.substr(7,t.length-1),o=["_local_"+n,"_from_"+n,"_to_"+n,n],a=0;_.each(o,function(e,t){_.each(r[o[a]].Current,function(e,t){i.Current[t]=e}),_.each(r[o[a]].Plan,function(e,t){i.Plan[t]=e}),delete r[o[a]],r[n]=i,a++})}});var t={};Object.keys(r).sort().forEach(function(e){t[e]=r[e]}),this.$el.html(this.template.render({collections:t,visible:this.visibleCollection})),1===$(".sectionShard").length&&$(".sectionHeader").first().click(),$(".innerContent").css("min-height","0px")},updateServerTime:function(){this.serverTime=(new Date).getTime()}})}(),function(){"use strict";window.ShowClusterView=Backbone.View.extend({detailEl:"#modalPlaceholder",el:"#content",defaultFrame:12e5,template:templateEngine.createTemplate("showCluster.ejs"),modal:templateEngine.createTemplate("waitModal.ejs"),detailTemplate:templateEngine.createTemplate("detailView.ejs"),events:{"change #selectDB":"updateCollections","change #selectCol":"updateShards","click .dbserver.success":"dashboard","click .coordinator.success":"dashboard"},replaceSVGs:function(){$(".svgToReplace").each(function(){var i=$(this),n=i.attr("id"),e=i.attr("src");$.get(e,function(e){var t=$(e).find("svg");t.attr("id",n).attr("class","icon").removeAttr("xmlns:a"),i.replaceWith(t)},"xml")})},updateServerTime:function(){this.serverTime=(new Date).getTime()},setShowAll:function(){this.graphShowAll=!0},resetShowAll:function(){this.graphShowAll=!1,this.renderLineChart()},initialize:function(e){this.options=e,this.interval=1e4,this.isUpdating=!1,this.timer=null,this.knownServers=[],this.graph=void 0,this.graphShowAll=!1,this.updateServerTime(),this.dygraphConfig=this.options.dygraphConfig,this.dbservers=new window.ClusterServers([],{interval:this.interval}),this.coordinators=new window.ClusterCoordinators([],{interval:this.interval}),this.documentStore=new window.ArangoDocuments,this.statisticsDescription=new window.StatisticsDescription,this.statisticsDescription.fetch({async:!1}),this.dbs=new window.ClusterDatabases([],{interval:this.interval}),this.cols=new window.ClusterCollections,this.shards=new window.ClusterShards,this.startUpdating()},listByAddress:function(t){var i=this;this.dbservers.byAddress({},function(e){i.coordinators.byAddress(e,t)})},updateCollections:function(){var i=this,n=$("#selectCol"),e=$("#selectDB").find(":selected").attr("id");if(e){var o=n.find(":selected").attr("id");n.html(""),this.cols.getList(e,function(e){_.each(_.pluck(e,"name"),function(e){n.append('")});var t=$("#"+o,n);1===t.length&&t.prop("selected",!0),i.updateShards()})}},updateShards:function(){var e=$("#selectDB").find(":selected").attr("id"),t=$("#selectCol").find(":selected").attr("id");this.shards.getList(e,t,function(e){$(".shardCounter").html("0"),_.each(e,function(e){$("#"+e.server+"Shards").html(e.shards.length)})})},updateServerStatus:function(e){function t(e,t,i){var n,o,a=i;a=(a=a.replace(/\./g,"-")).replace(/:/g,"_"),(o=$("#id"+a)).length<1||(n=o.attr("class").split(/\s+/)[1],o.attr("class",e+" "+n+" "+t),"coordinator"===e&&("success"===t?$(".button-gui",o.closest(".tile")).toggleClass("button-gui-disabled",!1):$(".button-gui",o.closest(".tile")).toggleClass("button-gui-disabled",!0)))}var i=this;this.coordinators.getStatuses(t.bind(this,"coordinator"),function(){i.dbservers.getStatuses(t.bind(i,"dbserver")),e()})},updateDBDetailList:function(){var i=this,n=$("#selectDB"),o=n.find(":selected").attr("id");n.html(""),this.dbs.getList(function(e){_.each(_.pluck(e,"name"),function(e){n.append('")});var t=$("#"+o,n);1===t.length&&t.prop("selected",!0),i.updateCollections()})},rerender:function(){var e=this;this.updateServerStatus(function(){e.getServerStatistics(function(){e.updateServerTime(),e.data=e.generatePieData(),e.renderPieChart(e.data),e.renderLineChart(),e.updateDBDetailList()})})},render:function(){this.knownServers=[],delete this.hist;var i=this;this.listByAddress(function(t){1===Object.keys(t).length?i.type="testPlan":i.type="other",i.updateDBDetailList(),i.dbs.getList(function(e){$(i.el).html(i.template.render({dbs:_.pluck(e,"name"),byAddress:t,type:i.type})),$(i.el).append(i.modal.render({})),i.replaceSVGs(),i.getServerStatistics(function(){i.data=i.generatePieData(),i.renderPieChart(i.data),i.renderLineChart(),i.updateDBDetailList(),i.startUpdating()})})})},generatePieData:function(){var t=[],i=this;return this.data.forEach(function(e){t.push({key:e.get("name"),value:e.get("system").virtualSize,time:i.serverTime})}),t},addStatisticsItem:function(e,t,i,n){var o=this;o.hasOwnProperty("hist")||(o.hist={}),o.hist.hasOwnProperty(e)||(o.hist[e]=[]);var a=o.hist[e],r=a.length;if(0===r)a.push({time:t,snap:n,requests:i,requestsPerSecond:0});else{var s=a[r-1].time,l=a[r-1].requests;if(l";return t&&(n+=''),i&&(n+=''+i.toUpperCase()+""),n+=""}$(this.el).html(this.template.render({})),$(this.el).show(),this.typeahead="aql"===i?$("#spotlight .typeahead").typeahead({hint:!0,highlight:!0,minLength:1},{name:"Functions",source:n.substringMatcher(n.aqlBuiltinFunctionsArray),limit:n.displayLimit,templates:{header:e("Functions","fa-code","aql")}},{name:"Keywords",source:n.substringMatcher(n.aqlKeywordsArray),limit:n.displayLimit,templates:{header:e("Keywords","fa-code","aql")}},{name:"Documents",source:n.substringMatcher(n.collections.doc),limit:n.displayLimit,templates:{header:e("Documents","fa-file-text-o","Collection")}},{name:"Edges",source:n.substringMatcher(n.collections.edge),limit:n.displayLimit,templates:{header:e("Edges","fa-share-alt","Collection")}},{name:"System",limit:n.displayLimit,source:n.substringMatcher(n.collections.system),templates:{header:e("System","fa-cogs","Collection")}}):$("#spotlight .typeahead").typeahead({hint:!0,highlight:!0,minLength:1},{name:"Documents",source:n.substringMatcher(n.collections.doc),limit:n.displayLimit,templates:{header:e("Documents","fa-file-text-o","Collection")}},{name:"Edges",source:n.substringMatcher(n.collections.edge),limit:n.displayLimit,templates:{header:e("Edges","fa-share-alt","Collection")}},{name:"System",limit:n.displayLimit,source:n.substringMatcher(n.collections.system),templates:{header:e("System","fa-cogs","Collection")}}),$("#spotlight .typeahead").focus()}.bind(this);0===n.aqlBuiltinFunctionsArray.length?this.fetchKeywords(o):o()}})}(),function(){"use strict";window.StatisticBarView=Backbone.View.extend({el:"#statisticBar",events:{"change #arangoCollectionSelect":"navigateBySelect","click .tab":"navigateByTab"},template:templateEngine.createTemplate("statisticBarView.ejs"),initialize:function(e){this.currentDB=e.currentDB},replaceSVG:function(i){var n=i.attr("id"),o=i.attr("class"),e=i.attr("src");$.get(e,function(e){var t=$(e).find("svg");void 0===n&&(t=t.attr("id",n)),void 0===o&&(t=t.attr("class",o+" replaced-svg")),t=t.removeAttr("xmlns:a"),i.replaceWith(t)},"xml")},render:function(){var e=this;return $(this.el).html(this.template.render({isSystem:this.currentDB.get("isSystem")})),$("img.svg").each(function(){e.replaceSVG($(this))}),this},navigateBySelect:function(){var e=$("#arangoCollectionSelect").find("option:selected").val();window.App.navigate(e,{trigger:!0})},navigateByTab:function(e){var t=(e.target||e.srcElement).id;return"links"===t?$("#link_dropdown").slideToggle(200):"tools"===t?$("#tools_dropdown").slideToggle(200):window.App.navigate(t,{trigger:!0}),void e.preventDefault()},handleSelectNavigation:function(){$("#arangoCollectionSelect").change(function(){var e=$(this).find("option:selected").val();window.App.navigate(e,{trigger:!0})})},selectMenuItem:function(e){$(".navlist li").removeClass("active"),e&&$("."+e).addClass("active")}})}(),function(){"use strict";window.StoreDetailView=Backbone.View.extend({el:"#content",divs:["#readme","#swagger","#app-info","#sideinformation","#information","#settings"],navs:["#service-info","#service-api","#service-readme","#service-settings"],template:templateEngine.createTemplate("storeDetailView.ejs"),remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,this},events:{"click #installService":"installService"},installService:function(){arangoHelper.createMountPointModal(this.installFoxxFromStore.bind(this))},installCallback:function(e){window.App.navigate("#services",{trigger:!0}),window.App.applicationsView.installCallback(e)},installFoxxFromStore:function(e){var t,i,n;window.modalView.modalTestAll()&&(this._upgrade?t=this.mount:"/"!==(t=window.arangoHelper.escapeHtml($("#new-app-mount").val())).charAt(0)&&(t="/"+t),i={name:this.model.get("name"),version:this.model.get("latestVersion")},n=arangoHelper.getFoxxFlags(),this.collection.install("store",i,t,n,this.installCallback.bind(this)),window.modalView.hide(),arangoHelper.arangoNotification("Services","Installing "+this.model.get("name")+"."))},resize:function(e){e?$(".innerContent").css("height","auto"):$(".innerContent").height($(".centralRow").height()-150)},render:function(){var n=this;return this.model.fetchThumbnail(function(e){var t=function(e,t){if(e)arangoHelper.arangoError("DB","Could not get current database");else{var i=this.model.get("defaultThumbnailUrl");if(this.model.get("manifest"))try{this.model.get("manifest").thumbnail&&(i=this.model.getThumbnailUrl())}catch(e){}$(this.el).html(this.template.render({app:this.model,baseUrl:arangoHelper.databaseUrl("",t),installed:!0,image:i})),this.model.fetchReadme(n.renderReadme)}this.breadcrumb()}.bind(this);arangoHelper.currentDatabase(t),_.isEmpty(this.model.get("config"))&&$("#service-settings").attr("disabled",!0)}.bind(this)),this.resize(!1),$(this.el)},renderReadme:function(e){var t=marked(e);$("#readme").html(t)},breadcrumb:function(){var e="Service: "+this.model.get("name")+'',t='
\n ',largeChart("requestsChart","Requests per Second"),__p+="\n\n ",tendency("Request Types","asyncRequests",!1),__p+="\n ",tendency("Number of Client Connections","clientConnections",!1),__p+='\n
\n \n
\n ',largeChart("dataTransferChart","Transfer Size per Second"),__p+="\n ",smallChart("dataTransferDistribution","Transfer Size per Second (distribution)",!1),__p+='\n
\n \n
\n ',largeChart("totalTimeChart","Average Request Time (seconds)"),__p+="\n ",smallChart("totalTimeDistribution","Average Request Time (distribution)",!1),__p+="\n
\n
\n "),__p+='\n
\n\n
\n\n
\n ',tendency("Number of threads","numberOfThreads",!1),__p+='\n\n
\n
\n
\n \n \n
\n
\n
\n \n
\n
\n
\n
Memory
\n
\n\n ',tendency("Virtual Size in GB","virtualSize",!1),__p+='\n
\n
\n ',mediumChart("pageFaultsChart","Major Page Faults"),__p+="\n ",mediumChart("systemUserTimeChart","Used CPU Time per Second"),__p+="\n
\n Download a Foxx service from a public github.com repository. In order to define a version please add a git tag to your repository using the following format: "v1.2.3". To connect to github your username and the name of the repository are sufficient.\n
\n
\n
\n
\n Repository*:\n
\n
\n \n
\n
\n
\n
\n Version*:\n
\n
\n \n
\n
\n
\n
\n Enable Legacy Mode:\n
\n
\n \n
\n
\n \n \n
\n
\n
\n
\n
\n\n
\n
\n
\nUpload a Foxx service bundle. The Foxx service bundle should be a zip archive containing all service files as a directory structure, including the manifest and any required node_modules dependencies. If your service doesn\'t have any dependencies, configuration or scripts you can also upload a single JavaScript file that will act as the service\'s entry point or "main" file.\n
The following information does not contain data stored in the write-ahead log. It can be inaccurate, until the write-ahead log has been completely flushed.
This node is not replicating from any other node. Also there are no active slaves or followers found. Please visit our Documentation to find out how to setup replication.
\n Download a Foxx service from a public github.com repository. In order to define a version please add a git tag to your repository using the following format: "v1.2.3". To connect to github your username and the name of the repository are sufficient.\n
\n Upload a Foxx service bundle. The Foxx service bundle should be a zip archive containing all service files as a directory structure, including the manifest and any required node_modules dependencies. If your service doesn\'t have any dependencies, configuration or scripts you can also upload a single JavaScript file that will act as the service\'s entry point or "main" file.\n
\n Download a Foxx service from a public available url. Access using credentials in the URL is allowed (https://username:password@www.example.com/). \n
\n If you are a Customer, please log-in to our Support Portal to request help.\n
\n\n
\n
Community Support
\n Join our experienced and growing community to get help, challenge ideas or discuss new features!\n \n
\n\n
\n Place for stars and reporting issues\n \n
\n\n
\n Ask questions and get answers\n \n
\n\n
\n Join a lively conversation about ArangoDB\n \n
\n\n
\n Challenge ideas and discuss upgrades\n \n
\n\n
\n
Want to shorten your development cycle or securing your production system?
\n Benefit from the deep understanding and decades of experience our core team has build up. Discuss architectures, data modeling, query optimization or anything you like. Get in contact for our individual development support, trainings or subscriptions.\n Contact us to get detailed infos for enterprises and special offers for startups.\n
\n\n
\n\n
\n\n
\n
\n\n
\n\n
\n\n
\n
Find manuals for ArangoDB, AQL, Foxx and many other useful resources
\n "),__p+="\n";return __p};
\ No newline at end of file
+this.JST=this.JST||{},this.JST["templates/applicationDetailView.ejs"]=function(obj){obj=obj||{};var __t,__p="",__e=_.escape,__j=Array.prototype.join;function print(){__p+=__j.call(arguments,"")}with(obj)__p+='
\n ',largeChart("requestsChart","Requests per Second"),__p+="\n\n ",tendency("Request Types","asyncRequests",!1),__p+="\n ",tendency("Number of Client Connections","clientConnections",!1),__p+='\n
\n \n
\n ',largeChart("dataTransferChart","Transfer Size per Second"),__p+="\n ",smallChart("dataTransferDistribution","Transfer Size per Second (distribution)",!1),__p+='\n
\n \n
\n ',largeChart("totalTimeChart","Average Request Time (seconds)"),__p+="\n ",smallChart("totalTimeDistribution","Average Request Time (distribution)",!1),__p+="\n
\n
\n "),__p+='\n
\n\n
\n\n
\n ',tendency("Number of threads","numberOfThreads",!1),__p+='\n\n
\n
\n
\n \n \n
\n
\n
\n \n
\n
\n
\n
Memory
\n
\n\n ',tendency("Virtual Size in GB","virtualSize",!1),__p+='\n
\n
\n ',mediumChart("pageFaultsChart","Major Page Faults"),__p+="\n ",mediumChart("systemUserTimeChart","Used CPU Time per Second"),__p+="\n
\n Download a Foxx service from a public github.com repository. In order to define a version please add a git tag to your repository using the following format: "v1.2.3". To connect to github your username and the name of the repository are sufficient.\n
\n
\n
\n
\n Repository*:\n
\n
\n \n
\n
\n
\n
\n Version*:\n
\n
\n \n
\n
\n
\n
\n Enable Legacy Mode:\n
\n
\n \n
\n
\n \n \n
\n
\n
\n
\n
\n\n
\n
\n
\nUpload a Foxx service bundle. The Foxx service bundle should be a zip archive containing all service files as a directory structure, including the manifest and any required node_modules dependencies. If your service doesn\'t have any dependencies, configuration or scripts you can also upload a single JavaScript file that will act as the service\'s entry point or "main" file.\n
The following information does not contain data stored in the write-ahead log. It can be inaccurate, until the write-ahead log has been completely flushed.
This node is not replicating from any other node. Also there are no active slaves or followers found. Please visit our Documentation to find out how to setup replication.
\n Download a Foxx service from a public github.com repository. In order to define a version please add a git tag to your repository using the following format: "v1.2.3". To connect to github your username and the name of the repository are sufficient.\n
\n Upload a Foxx service bundle. The Foxx service bundle should be a zip archive containing all service files as a directory structure, including the manifest and any required node_modules dependencies. If your service doesn\'t have any dependencies, configuration or scripts you can also upload a single JavaScript file that will act as the service\'s entry point or "main" file.\n
\n Download a Foxx service from a public available url. Access using credentials in the URL is allowed (https://username:password@www.example.com/). \n
\n If you are a Customer, please log-in to our Support Portal to request help.\n
\n\n
\n
Community Support
\n Join our experienced and growing community to get help, challenge ideas or discuss new features!\n \n
\n\n
\n Place for stars and reporting issues\n \n
\n\n
\n Ask questions and get answers\n \n
\n\n
\n Join a lively conversation about ArangoDB\n \n
\n\n
\n Challenge ideas and discuss upgrades\n \n
\n\n
\n
Want to shorten your development cycle or securing your production system?
\n Benefit from the deep understanding and decades of experience our core team has build up. Discuss architectures, data modeling, query optimization or anything you like. Get in contact for our individual development support, trainings or subscriptions.\n Contact us to get detailed infos for enterprises and special offers for startups.\n
\n\n
\n\n
\n\n
\n
\n\n
\n\n
\n\n
\n
Find manuals for ArangoDB, AQL, Foxx and many other useful resources